Reputation: 539
I have an array of buttons and I want to add an eventListener to each of them.
In the eventListener, I want to retrieve the width value of the button that is currently being pressed. How can I do that?
for (i=0; i<5; i++) {
button[i].addEventListener(click, function(e) {
alert(/*How should I refer to THAT button*/)
})
}
Upvotes: 1
Views: 1322
Reputation: 348992
Inside the event listener, you can use this
to refer to the current button:
for (var i=0; i<5; i++) {
button[i].addEventListener('click', function(e) {
alert( this ); // <-- This inside the event listener = current button
});
}
Another method is to wrap the loop's body in a closure, and create a local variable:
for (var i=0; i<5; i++) {
(function(button) { // <--- Local variable
button.addEventListener('click', function(e) {
alert( button );
});
})(button[i]); // <-- Pass button
}
Instead of constructing a new function at each loop, you can also create a named function outside the loop:
function createButtonEvent(button) {
button.addEventListener('click', function(e) {
alert( button );
});
}
for (var i=0; i<5; i++) {
createButtonEvent(button[i]);
}
Upvotes: 5