I've been working on this extensively for the past week and I can not figure out why this does not work.
I'm trying to use an external javascript file to pull all img tags on the html page and swap out the images dynamically (by changing the src) when a user hovers over the image with their mouse. I can change the image when the user hovers over the image, but when it changes back, it does not coordinate with the correct image (image 1,2,3,4 will all change to image 5).
Here's the html.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="JS1.js" type="text/javascript" /></script>
<title>main</title>
</head>
<body>
<div id="divCont">
<img src="images/button1_out.gif" id="button1" /> <br />
<img src="images/button2_out.gif" id="button2" /> <br />
<img src="images/button3_out.gif" id="button3" /> <br />
<img src="images/button4_out.gif" id="button4" /> <br />
<img src="images/button5_out.gif" id="button5" /> <br />
</div>
</body>
</html>
Here's the javascript:
window.onload = function()
{
var arrImgs = document.getElementsByTagName("img");
for(var i = 0; i < arrImgs.length; i++) {
var elemImg = arrImgs[i];
//alert(elemImg.id);
elemImg.onmouseover = function() {
//alert(this.src);
//var targetId = this.src;
this.src = "images/" + elemImg.id + "_over.gif";
//alert(this.src);
}
elemImg.onmouseout = function() {
//alert(this.src);
this.src = "images/" + elemImg.id + "_out.gif";
}
}
}
Here's why this is happening - after you have created your event handlers, they still reference the elemImg variable. At the end of your loop, that variable is equal to the LAST thing you set it to (the 5th element). So any reference to elemImg executed later will reference the 5th element.
Here's how to fix it: in your mouseout/mouseover functions, use "this.id" instead of "elemImg.id".