Possible Duplicate:
How to pass arguments to addEventListener listener function?
How can I pass some argument (in this case an integer) to a function through addEventListener
on a click
event?
I have two buttons; if I press the right one I want to do some stuff, if I press the left one then I'd like it to do something else.
Here's the code:
document.getElementById('date_right').addEventListener( 'click', switch_date(1), false );
document.getElementById('date_left').addEventListener( 'click', switch_date(-1), false );
function switch_date( k )
{
if(k==1)
{
//do stuff
}
else
{
//another stuff
}
}
Here is the code: var someVar = some_other_function(); someObj. addEventListener("click", function(){ some_function(someVar); }, false);
If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.
We can invoke multiple functions on a single event listener without overwriting each other. To do this we simply call the addEventListener() method more than once with a different function. In the example above, we add another event listener for the same event on the same button.
You don't. Use anonymous functions:
document.getElementById('date_right').addEventListener('click', function () {
switch_date(1);
}, false);
document.getElementById('date_left').addEventListener('click', function () {
switch_date(-1);
}, false);
Or use named functions which do not take arguments:
function onRightDateClick() {
switch_date(1);
}
function onLeftDateClick() {
switch_date(-1);
}
document.getElementById('date_right').addEventListener('click', onRightDateClick, false);
document.getElementById('date_left').addEventListener('click', onLeftDateClick, false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With