0

Okey so I got this following javaScript code.

function test(id)
{
alert(id);
}


var elem = document.getElementsByClassName('outsideDiv');

for(var i=0; i < elem.length; i++)
{
elem[i].addEventListener('mouseover', function(){test(i);}, false);
}

this gives all divs with the class a mouse over but the function always returns the latest i index. in this case i got 5 div elements and the alert is allways 5 no mather witch one i hover. Can anyone explain why?

user1593846
  • 734
  • 1
  • 15
  • 34
  • 1
    duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example), [infamous loop problem](http://stackoverflow.com/questions/1451009/javascript-infamous-loop-problem) and thousands others – Bergi Dec 12 '12 at 18:55

1 Answers1

1

Try using this instead:

function mouseOverFunc(i) {
    return function () {
        test(i);
    };
}

function test(id) {
    alert(id);
}

var elem = document.getElementsByClassName('outsideDiv');

for(var i=0; i < elem.length; i++) {
    elem[i].addEventListener('mouseover', mouseOverFunc(i), false);
}

Just because you add event listeners to the elements doesn't mean the value of i is preserved for each listener. You need to create a closure that will create a new scope with i.

The reason this is happening is because the function bound to each listener is just a reference. When the event happens (mouseover), the function is finally called, but what's the value of i? The for loop finished executing a long time ago, so the value of i is the end value - 5.

Ian
  • 50,146
  • 13
  • 101
  • 111