[Solved] Multiple image rollover in javascript with for loop


I would recommend you don’t include inline event attributes at each element. But I would consider including an inline html5 data- attribute with the message associated with the elements:

<img src="https://stackoverflow.com/questions/24593698/images/img1.jpg" data-msg="Hi, How r u?" width="100" height="100">
<!-- etc -->

Then you can bind the same rollover functions to each element using a loop as follows:

function doMouseOver(e) {
    document.getElementById("displayText1").innerHTML =
                                    e.target.getAttribute("data-msg");
    document.getElementById("displayText").style.visibility='visible';
}
function doMouseOut() {
    document.getElementById("displayText").style.visibility='hidden';
}

var imgs = document.getElementsByTagName("img"),
    i;
for (i = 0; i < imgs.length; i++) {
    imgs[i].addEventListener("mouseover", doMouseOver);
    imgs[i].addEventListener("mouseout", doMouseOut);
}

Within the doMouseOver() function, the e argument is the event object, and thus e.target gives you a reference to the element the event happened to – so then you can retrieve the particular data-msg value for that element to display it.

Demo: http://jsfiddle.net/3c7Rb/

Having said that, you don’t need the loop either. You can bind the functions directly to the document, and then within the mouse over handler you simply test whether the target element has the msg-data attribute. If it does, display it, otherwise do nothing:

function doMouseOver(e) {
    var msg = e.target.getAttribute("data-msg");
    if (msg) {
        document.getElementById("displayText1").innerHTML= msg;
        document.getElementById("displayText").style.visibility='visible';
    }
}
function doMouseOut() {
    document.getElementById("displayText").style.visibility='hidden';
}

document.addEventListener("mouseover", doMouseOver);
document.addEventListener("mouseout", doMouseOut);

Demo: http://jsfiddle.net/3c7Rb/1/

solved Multiple image rollover in javascript with for loop