What actually happens in the line elem.addEventListener("keyup",alert(i))
is that the function-call alert(i)
is executed and the return value of that function call is then added as an event listener. This obviously doesn't make sense, because 1. alert
doesn't return anything and 2. you only want to execute it when the event happens.
What you actually seem to want to do is bind the function-call alert(i)
itself to the event listener, not its return value.
You could assign the alert-function to the keyup event using elem.addEventListener("keyup",alert)
. But in that case you can't pass any arguments to it. If you want to do this, you can use Function.bind
to create a new function from a function and a list of arguments.
elem.addEventListener("keyup", alert.bind(null, i))
If you need to support old browsers which do not support bind
yet, this is an alternative syntax which generates an anonymous function as an event handler:
elem.addEventListener("keyup", function() {
alert(i);
})
There is, however, another issue with your code. Every event handler will have the same value for i
. Check the question mentioned by Sterling Archer's comment on the question for a solution.