0

I've different images and I want to draw some informations about every image in a div below the image. The div IDs are "pic0", "pic1" ...

My first question is: how do I know which image is hovered? This is my try:

window.onload = function() { 
    var tags = document.getElementsByTagName('IMG');
    for (var i = 0; i < tags.length; i++) {
        tags[i].onmouseover = function() {
            alert("Hovered" + i);
        };
    }
};

It only shows the number of images but not the one hovered.

My second question is: how can I get the number of the hovered image to a variable to draw the information about the image like this: document.getElementById("pic" + i).innerHTML ...

This is the HTML-Code

<!DOCTYPE html> 
<html lang="de"> 
<head> 
    <meta charset="utf-8"> 
    <title>AJAX</title> 
    <meta name="viewport" content= "width=device-width; initial-scale=1.0"> 
    <link rel="stylesheet" type="text/css" href="lib/css/stil.css" /> 
    <script type="text/javascript" src="lib/js/test.js"></script> 
</head> 
<body> 
    <h1>hello world</h1> 
    <table> 
        <tr> 
            <td><img src="img/b1.jpg" /></td>
            <td id="pic0"></td> 
        </tr> 
        <tr> 
            <td><img src="img/b2.png" /></td> 
            <td id="pic1"></td> 
        </tr>
        <tr> 
            <td><img src="img/b3.jpg" /></td> 
            <td id="pic2"></td> 
        </tr> 

...

    </table> 
</body> 
</html>

I appreciate any help or hints you can give me :)

Desolator
  • 1
  • 1
  • `for (let i = 0; ...` does the trick. That means you've to use a block scoped variable, `var` creates a variable to the function scope. – Teemu Nov 06 '17 at 12:35
  • Please add a minimal, complete, verifiable example as outlined here: https://stackoverflow.com/help/mcve – Thijs Nov 06 '17 at 12:38
  • The problem is that `i` keeps incrementing while the loop is running, meaning that all the callbacks eventually reference the same `i`. which at that time will equal `tags.length` – Cerbrus Nov 06 '17 at 12:46

0 Answers0