Jouh
Jouh

Reputation: 74

Adding parameter to callback function within a for loop

I tried to get similiar questions to this one, but was unable to find a solution that fits me. I have the following code

for(var i=0; i<keys.length; i++) {
    document.getElementById("btn_"+keys[i]).addEventListener('click', function(){changeTab(keys[i]);});
}

Now executing this leave keys[i] in the callback, what I obviously do not want. I need to be able to loop through the keys array and pass the current value to the function call within the callback. How can I fix/ achieve this?

Upvotes: 0

Views: 49

Answers (2)

Matt
Matt

Reputation: 396

The event is also passed to the event handler. You can get the target element from there, like so:

addEventListener('click', function (event) {
  changeTab( event.target );
});`

Alternatively, you can wrap the callback in a separate scope to retain the value of i, as seen in this answer

Upvotes: 1

Jouh
Jouh

Reputation: 74

I managed to accomplish this by using an outer function accepting the parameter.

for(var i=0; i<keys.length; i++) {
    !function outer(i){
        document.getElementById("btn_"+i).addEventListener('click', function(){changeTab(i);})
    }(keys[i])
}

Upvotes: 0

Related Questions