Home > Mobile >  Pass a counter from a for loop into an event listener
Pass a counter from a for loop into an event listener

Time:09-09

I'm trying to pass the counter into an event listener's parameter function. I know it is possible using an anonymous function for the click event but wanted to use a named function instead. I can't seem to figure this out or if it is possible. Is there any way to do this?

function addKeys(){
    for(let i = 0; i < keys.length; i  ){
        keys[i].addEventListener("click", testing)
    }
}

function testing(e){
    console.log(e)
    console.log(i)
}

CodePudding user response:

You can bind a parameter to the function:

keys[i].addEventListener("click", testing.bind(null, i))

Now i will be passed as the first parameter, before any others:

function testing(i, e) {
  ...
}
  • Related