Calling arguments in an event handler

the function simulateClick on the sample page shows you can pass in a set of arguments

function simulateClick(first argument, second argument) {

document.getElementById("button").addEventListener('click', simulateClick);
// document.getElementById("button").addEventListener('click', simulateClick,(first argument, second argument));

but as soon as I try to add the parentheses for a set of arguments in the call, it tends to be called on page load, so what would be the correct syntax I am supposed to use to add a aset of arguments to the call?

function simmulateClick(arg_1,arg_2){  
//some code here  
}

function anotherFunction(){
 document.getElementById("button").addEventListener('click', simulateClick(pass_arg_1,pass_arg_2)); 
}

The handler function by itself always gets passed in the event object as its only argument. If you want to pass additional arguments, you basically have two options… you can either .bind() additional arguments, which will get prepended to the actual argument:

var handleClick = function (additionalArg, event) {
  console.log(additionalArg, event) // "foo", MouseEvent
}

myElement.addEventListener('click', handleClick.bind(myElement, 'foo'))

Or you can call a function that returns the actual handler, creating a closure where the additional arguments get captured:

var getClickHandler = function (arg) {
  return function handleClick (event) {
    console.log(arg, event) // "foo", MouseEvent  
  }
}

myElement.addEventListener('click', getClickHandler('foo'))
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.