How to pass arguments to addEventListener listener function?

Abhishek Yadav picture Abhishek Yadav · Nov 2, 2008 · Viewed 486.7k times · Source

The situation is somewhat like-

var someVar = some_other_function();
someObj.addEventListener("click", function(){
    some_function(someVar);
}, false);

The problem is that the value of someVar is not visible inside the listener function of the addEventListener, where it is probably being treated as a new variable.

Answer

Zaloz picture Zaloz · Aug 16, 2012

Why not just get the arguments from the target attribute of the event?

Example:

const someInput = document.querySelector('button');
someInput.addEventListener('click', myFunc, false);
someInput.myParam = 'This is my parameter';
function myFunc(evt)
{
  window.alert(evt.currentTarget.myParam);
}
<button class="input">Show parameter</button>

JavaScript is a prototype-oriented language, remember!