Sometimes, we want to pass an event object to a function in JavaScript.
In this article, we’ll look at how to pass an event object to a function in JavaScript.
How to pass an event object to a function in JavaScript?
To pass an event object to a function in JavaScript, we can use the addEventListener method.
For instance, we write
const onClick = (ev) => {
ev.preventDefault();
console.log("Hello World!");
};
document.getElementById("my_button").addEventListener("click", onClick);
to select the element with getElementById.
And then we add a click event listener to it with addEventListener.
We set the onClick function as the click event listener.
It takes the ev event object as its argument.
Conclusion
To pass an event object to a function in JavaScript, we can use the addEventListener method.