Categories
JavaScript Answers

How to pass an event object to a function in JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *