2

I have a webpage with many images, each of which has a title attribute. When I hover over the image, I want the title text to display in a separate legend element I have created (not as a tiny hover tooltip). I have a mouseover function which works fine - i.e. when I hover over the image the legend changes value. But I want that value to be the title text of the individual image - which I don't know how to access. I have tried …innerHTML = this.title which is obviously incorrect.

[The number of images is large and changing (like an album), so I can't add separate code for each <img> tag. I can use alt or any other <img> attribute to make this work. I'm not wedded to the innerHTML method, either, but am hoping for some simple code to do the trick!]

Please help? Thanks! (FYI, I'm a novice coder.)

<!DOCTYPE html>
<html>
<body>

  <h1 id="legend">title appears here</h1>

  <div>
    <img src="image1.jpg" onmouseover="mouseOver()" title="Breakfast">
    <img src="image2.jpg" onmouseover="mouseOver()" title="Lunch">
    <img src="image3.jpg" onmouseover="mouseOver()" title="Dinner">
  </div>

  <script>
    function mouseOver() {
        document.getElementById("legend").innerHTML = this.title;
    }
  </script>

</body>
</html>
codeR
  • 21
  • 4

2 Answers2

2

It looks like you are trying to use this.title to represent the different images? If you want their titles to appear in the <h1> tag you need to pass the information to the function shown below.

 <h1 id="legend">title appears here</h1>

  <div>
    <img src="image1.jpg" onmouseover="mouseOver(this)" title="Breakfast">
    <img src="image2.jpg" onmouseover="mouseOver(this)" title="Lunch">
    <img src="image3.jpg" onmouseover="mouseOver(this)" title="Dinner">
  </div>

  <script>
    function mouseOver(x) {
        document.getElementById("legend").innerHTML = x.title;
    }
  </script>
Scath
  • 3,777
  • 10
  • 29
  • 40
0

I guess its helpful .

But i use Jquery just need call this code in your <head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <!DOCTYPE html>
    <html>
    <head>
    <script 
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    </head>
    <body>

      <h1 id="legend">title appears here</h1>

      <div>
        <img src="image1.jpg" class="class_of_div" title="Breakfast">
        <img src="image2.jpg" class="class_of_div" title="Lunch">
        <img src="image3.jpg" class="class_of_div" title="Dinner">
      </div>

      <script>
        $(document).on('mouseover', '.class_of_div', function () {
            var thiss=$(this);
            $('#legend').text(thiss.attr('title'));
        });
      </script>

    </body>
    </html>
BenyaminRmb
  • 163
  • 4
  • 15