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?
Try using this instead:
Just because you add event listeners to the elements doesn’t mean the value of
iis preserved for each listener. You need to create a closure that will create a new scope withi.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? Theforloop finished executing a long time ago, so the value ofiis the end value –5.