Skip to content Skip to sidebar Skip to footer

Multiple Different Event Listeners In For Loop

The code below always returns undefined. Why is this? I want the event listener to respond with the string of the index. Thanks var array = ['Hey', 'Hi', 'Hello']; for (var i = 0;

Solution 1:

You need to wrap the click handler in a closure, to create a local copy of i:

box.addEventListener("click", (function(i) { 
  returnfunction() {
    alert(array[i]);
  }
})(i), false);

Fiddle

The way your code is now, i ends up with a value of 3, and array[3] is of course undefined. The above creates 3 copies of i with values 0, 1, 2.

Solution 2:

Possibly the simplest solution would be this:

box.addEventListener("click", alert.bind(window, array[i]), false);

But this won't work in IE<9.

Post a Comment for "Multiple Different Event Listeners In For Loop"