actionM
01-30-2009, 03:02 PM
Hey, I'm new here! On to the question. Why are the 2 examples of JavaScript that I have below, not exactly the same? The first one works as I wanted it to; it makes each image have a mouseover state that triggers an alert that displays a 0, 1, 2, or 3 for each image. However, the second example doesn't do that at all. The alert for each image is 4.
Why are they different? How can I get the second JS example do exactly as the first? Also, any other JS tips you can give to make my code better would be appriciated. Thank you.
Here is the relevant HTML:
<div id="darkBox">
<a href="pics/1big.jpg"><img src="pics/1small.jpg" /></a>
<a href="pics/2big.jpg"><img src="pics/2small.jpg" /></a>
<a href="pics/3big.jpg"><img src="pics/3small.jpg" /></a>
<a href="pics/4big.jpg"><img src="pics/4small.jpg" /></a>
</div><!-- end of id darkBox -->
Javascript 1:
function showBigImg(x) {
alert(x);
}
var darkBoxImg = document.getElementById("darkBox").getElementsByTagName("img");
darkBoxImg[0].addEventListener("mousemove",function(){showBigImg(0)},false);
darkBoxImg[1].addEventListener("mousemove",function(){showBigImg(1)},false);
darkBoxImg[2].addEventListener("mousemove",function(){showBigImg(2)},false);
darkBoxImg[3].addEventListener("mousemove",function(){showBigImg(3)},false);
Javascript 2:
function showBigImg(x) {
alert(x);
}
var darkBoxImg = document.getElementById("darkBox").getElementsByTagName("img");
var i = 0
for (i = 0; i < darkBoxImg.length; i++) {
darkBoxImg[i].addEventListener("mousemove",function(){showBigImg(i)},false);
}
Why are they different? How can I get the second JS example do exactly as the first? Also, any other JS tips you can give to make my code better would be appriciated. Thank you.
Here is the relevant HTML:
<div id="darkBox">
<a href="pics/1big.jpg"><img src="pics/1small.jpg" /></a>
<a href="pics/2big.jpg"><img src="pics/2small.jpg" /></a>
<a href="pics/3big.jpg"><img src="pics/3small.jpg" /></a>
<a href="pics/4big.jpg"><img src="pics/4small.jpg" /></a>
</div><!-- end of id darkBox -->
Javascript 1:
function showBigImg(x) {
alert(x);
}
var darkBoxImg = document.getElementById("darkBox").getElementsByTagName("img");
darkBoxImg[0].addEventListener("mousemove",function(){showBigImg(0)},false);
darkBoxImg[1].addEventListener("mousemove",function(){showBigImg(1)},false);
darkBoxImg[2].addEventListener("mousemove",function(){showBigImg(2)},false);
darkBoxImg[3].addEventListener("mousemove",function(){showBigImg(3)},false);
Javascript 2:
function showBigImg(x) {
alert(x);
}
var darkBoxImg = document.getElementById("darkBox").getElementsByTagName("img");
var i = 0
for (i = 0; i < darkBoxImg.length; i++) {
darkBoxImg[i].addEventListener("mousemove",function(){showBigImg(i)},false);
}