Reputation: 488
I'm currently learning Javascript, and now I'm messing around with eventlisteners.
But I have a problem, when I make the eventlisteners in a loop, I can't figure out how to pass it a variable that persists with it. I have made a script that moves a element to a specified position when I click it. But now it puts all the elements in the same position, so for some reason they are all getting the same numbers.
No matter if I pass it in as this:
var index = i;
applications[i].addEventListener('click', function(){
var posLeft2 = 10*index+"%";
var iconstyleO = " text-align: center; "+
" font: bold 22px Tahoma; "+
" position:fixed; "+
" top: 67%; "+
" left: "+posLeft2+"; "+
" display:block; "+
" margin: 150px auto; "+
" color: #ffffff; "+
" z-index: 3; "+
" -webkit-border-radius: 10px; "+
" background: rgb(140,140,140); "+
" width: 10%; "+
" height: 10%; ";
this.setAttribute('style',iconstyleO);
} ,false);
or like this:
var index = i;
applications[i].addEventListener('click', function(index){
var posLeft2 = 10*index+"%";
var iconstyleO = " text-align: center; "+
" font: bold 22px Tahoma; "+
" position:fixed; "+
" top: 67%; "+
" left: "+posLeft2+"; "+
" display:block; "+
" margin: 150px auto; "+
" color: #ffffff; "+
" z-index: 3; "+
" -webkit-border-radius: 10px; "+
" background: rgb(140,140,140); "+
" width: 10%; "+
" height: 10%; ";
this.setAttribute('style',iconstyleO);
} ,false);
They are still setting the eventlisteners to the same position. Either at the last elements position, or at the first elements position, depending on how I try to pass it in.
Any ideas?
Upvotes: 2
Views: 630
Reputation: 888303
Javascript does not have block scope.
Therefore, all of your callbacks are sharing the same variable.
To fix this, you need to wrap your code in an IIFE, so that each callback gets its own closure:
(function(index) {
applications[i].addEventListener('click', function(){
...
});
})(i);
Upvotes: 4