Click to See Complete Forum and Search --> : Assiging functions in a loop


alexxz4
March 25th, 2009, 04:11 PM
Hi,

This is bugging me. I have a bunch of div's and I am trying to assign each a few of functions in a loop.

var elems=document.getElementsByTagName("div");
for(var i=0;i<elems.length;i++){
elems[i].onclick=function(){load(elems[i]);};
elems[i].onmouseenter=function(){show(elems[i]);};
elems[i].onmouseleave=function(){hide(elems[i]);};
}

However, function load always receives the same index (which is the size of elems array). Thus the argument is undefined. Is there a way to assign functions in a loop instead of pasting the same three function in all divs in the HTML?

PeejAvery
March 25th, 2009, 05:08 PM
The only thing wrong with the actual code you have posted is that there are no events named onmouseenter nor onmouseleave. Those should be onmouseover and onmouseout.

Also, you don't need the semicolons after the brackets...just after the code inside of the brackets.

alexxz4
March 26th, 2009, 09:00 PM
Thanx for fixing up minor details (which are irrelevant to my problem).
Now to my problem: If you try this code (yeah I know I didnt include <head>, <!DOCTYPE> or <meta>, so no need to point it out):

<html>
<div>A</div><div>B</div><div>C</div><div>D</div>
<script type="text/javascript">
var elems=document.getElementsByTagName("div");
for(var i=0;i<elems.length;i++){
elems[i].onclick=function(){alert(i);}
}
</script>
</html>

if you click on any of the letters, you always get "4". It seems like the function is assigned after the loop is done, or maybe "i" is like a pointer. Not sure. But it would be nice if there was a way to fix this.
By the way, I noticed that .NET acts the same way with delegates. So its probably a design feature...

PeejAvery
March 27th, 2009, 08:17 AM
Actually, it is relevant to your problem to an extent. Since those methods don't exist, then they won't work.

Anyway, the reason why the alert always returns 4 is because the value of i is 4. You are telling it to return the value of a variable. It isn't anything tied to the actual DIV unless you assign the value to the div. This is an example of where you need to use this to point to the object's self.

Take the following code for example...

<html>
<head>
<script type="text/javascript">
function init() {
var elems=document.getElementsByTagName("div");
for(var i=0;i<elems.length;i++){
elems[i].onclick = function() {alert(this.innerHTML);};
}
}
window.onload = init;
</script>
</head>
<body>

<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>

</body>
</html>