What are custom events in JavaScript?

What are custom events in JavaScript?

Custom events are the events that allow you to decouple the code you want to run after a specific piece of code runs. There are various in-built events present in JavaScript such as on-click events and many more but what if we want to create a custom event that will trigger whenever we want and do whatever we want to do then the custom events come into the picture.

We can basically add custom events by adding an HTML event to an element of your web page. We can add a custom event either by using the Event constructor or by using the CustomEvent interface. Both of these produce the same custom event, but just the difference is that the CustomEvent interface allows you to add more functionality to the custom event.

In this tutorial, we will look at what are the custom events in JavaScript. Now we are going to create a custom event using both the methods as given below −

Using the Event Constructor

In this method, we first create a new event using an event constructor and then listen to it using an event listener, and at last, we trigger it using the dispatchEvent() method.

Syntax

Following is the syntax for a custom event using the event constructor in JavaScript −

const first = new Event("custom",{
   bubbles: true,
   cancelable: true,
});
document.addEventListener("custom", () => {
   document.write("The custom event was triggered")
});
document.dispatchEvent(first);

Using the Event Custom Interface

In this method also we first create a new event using event constructor and then listen to it using an event listener and at last we trigger it using dispatchEvent() method but here we can also add some conditions in the event listeners to make custom event more customizable.

Syntax

Following is the syntax to create a custom event using the event custom interface In JavaScript −

const first = new Event("custom",{
   bubbles: true,
   cancelable: true,
});
document.addEventListener("custom", () => {
   detail: { name: "John" }});
document.dispatchEvent(first);

Note → bubbles: true/false − if true, then the event bubbles.

cancelable − true/false − if true, then the “default action” may be prevented. Later we’ll see what it means for custom events.

By default, both are false: {bubbles: false, cancelable: false}.