Reputation: 61
In order to pass the event information to the change function, I have to call change function from the event listener without parenthesis.
var boxes = document.getElementsByClassName('boxes');
for(var i = 0; i < boxes.length; i++){
boxes[i].addEventListener('click', change, false);
}
function change(e){
e.target.style.border = '1px solid red';
}
The issue comes when i then want to pass in an argument as well as passing the event. It seems when adding an argument the event fails.
How would i be able to include something like this where the event is passed to change the border but am also able to pass arguments into the function?
var boxes = document.getElementsByClassName('boxes');
for(var i = 0; i < boxes.length; i++){
boxes[i].addEventListener('click', change(10, 20), false);
}
function change(e, a, b){
e.target.style.border = '1px solid red';
console.log(a * b);
}
Any help would be great!
Upvotes: 1
Views: 107
Reputation: 3485
var changeFn = function (e) {
change(e, 10, 20);
};
now add this to your click event
boxes[i].addEventListener('click', changeFn, false);
remove event listener is simple in this case
boxes[i].removeEventListener('click', changeFn, false);
Upvotes: 0
Reputation: 141839
Pass it an anonymous function:
boxes[i].addEventListener('click', function ( e ) { change(e, 10, 20) }, false);
Upvotes: 2