Sometimes, we want to add event handler with parameters with JavaScript.
In this article, we’ll look at how to add event handler with parameters with JavaScript.
How to add event handler with parameters with JavaScript?
To add event handler with parameters with JavaScript, we can create a function that takes the parameters we want.
For instance, we write
const addClickHandler = (elem, arg1, arg2) => {
elem.addEventListener(
"click",
(e) => {
// ...
},
false
);
};
to define the addClickHandler
function that takes a few parameters.
In it, we call elem.addEventListener
to add a click event listener to the elem
element.
We can do whatever we want with arg1
and arg2
in the click listener callback.
Conclusion
To add event handler with parameters with JavaScript, we can create a function that takes the parameters we want.