Bill Demaria Bill Demaria - 3 months ago 12
Javascript Question

Javascript Loop to Call a Function

Trying to figure out onmouseover, onmouseout and onclick with several pictures all having the same ID tag. To do that, I understand I need a .length loop.

This code works without the length loop...

window.onload = setPictures;
function setPictures() {
var img = document.getElementById("pictureBox");
img.onmouseover = mouseOverImage;
img.onmouseout= mouseOutImage;
}
function mouseOverImage() {
var img = document.getElementById("myImg");
img.style.opacity = .5;
}
function mouseOutImage() {
var img = document.getElementById("myImg");
img.style.opacity = 1;
}


This is the loop function I attempted that is not working.

window.onload = setPictures;
function setPictures() {
var img = document.getElementById("pictureBox");
for (var i=0; i<img.length; i++) {
img[i].onmouseover = mouseOverImage;
img[i].onmouseout= mouseOutImage;}
}


Please advise, and thank you in advance for your help!

Answer

getElementById only returns one element, as ID's should be unique.

Instead, add a class to each element and select them by class. Callbacks can rely on this's context for your mouse events:

function mouseOverImage() {
    this.style.opacity = .5;
}
function mouseOutImage() {
    this.style.opacity = 1;
}

window.onload = function setPictures() {
    var imageCollection = document.getElementsByClassName('pictureBox');
    for (var i=0; i < imageCollection.length; i++) {       
        imageCollection[i].onmouseover = mouseOverImage;
        imageCollection[i].onmouseout = mouseOutImage;
    }
 }