Categories
JavaScript Answers

How to add JavaScript custom Event Listener?

Spread the love

Sometimes, we want to add JavaScript custom Event Listener.

In this article, we’ll look at how to add JavaScript custom Event Listener.

How to add JavaScript custom Event Listener?

To add JavaScript custom Event Listener, we call addEventListener.

For instance, we write

const evt = document.createEvent("Event");
evt.initEvent("myEvent", true, true);
evt.foo = "bar";

document.addEventListener("myEvent", myEventHandler, false);

document.dispatchEvent(evt);

to add a listener for myEvent triggered by document.

We create the event with createEvent.

Then we call initEvent to set the event name.

And we add some properties to it with

evt.foo = "bar";

Then we call dispatchEvent to trigger the event.

Conclusion

To add JavaScript custom Event Listener, we call addEventListener.

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 *