Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass some parameters to function called in addEventListener? [duplicate]

Tags:

javascript

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
  }
}
like image 462
lwiii Avatar asked Nov 26 '12 18:11

lwiii


People also ask

How do you pass parameters to a function in addEventListener?

Here is the code: var someVar = some_other_function(); someObj. addEventListener("click", function(){ some_function(someVar); }, false);

How do you pass parameters to an event handler?

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.

How do I add multiple functions in addEventListener?

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.


1 Answers

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);
like image 138
Matt Ball Avatar answered Sep 20 '22 14:09

Matt Ball