I was writing a code that basically adds event listeners that call a function with the a fragment of their dom object's id, but every time I click an object with the listener It just gives me the same value no matter what object I click. Here's my code:
//add events
for (a=0; a<=tab_array.length-3; a++)
{
alert(a);
document.getElementById("mini_"+a).addEventListener("click",function(){open_tab(a)},false);
}
function open_tab(e)
{
//change across settings ect
alert("tab "+e+" clicked");
}
I realize it probably has something to do with pointers and that fact its using an anonymous function instead of directing passing a, but I just don't know what to do instead.
Your guess is correct. The behavior you see is because of your scope.
When your link is clicked javascript is passing the current value of a.
This value is tab_array.length-2 instead of the value a had during the loop run 0, 1 ....
To keep the value of a you have to create a new variable in a new scope (closure). E.g. e:
for (a=0; a<=tab_array.length-3; a++)
{
function(e){
document.getElementById("mini_"+e).addEventListener("click",function(){open_tab(e)},false);
}(a));
}
Another way would be to write a function which returns your handler inside its own scope:
//add events
for (a=0; a<=tab_array.length-3; a++)
{
alert(a);
document.getElementById("mini_"+a).addEventListener("click", open_tab(a) ,false);
}
function open_tab(e) {
return function() {
//change across settings ect
alert("tab "+e+" clicked");
}
}
See my fiddle or the Closure guide
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With