Return to Home Page...

DOM Custom Events

What is a custom event?

A custom event is an event that is created by a developer that monitors actions that aren't pre-built into the DOM's API. These events can be specified with specific details, and have various boolean values for certain properties, like 'bubbles', 'cancelable', and 'composed', all of which can affect how an event functions, and the path the DOM takes to register the event.

How does one create custom events?

There are two different methods to create custom events, both of which are fairly similar. One can use an Event constructor, where you define a new variable and store it as an event.

const newEvent = new Event('newEvent', {

bubbles: true,

cancelable: true,

composed: false;

})

Another way is to use the CustomEvent constructor, functioning similarly to the one as the one listed above.

const newEvent = new CustomEvent('newEvent', {

detail: {},

bubbles: true,

cancelable: true,

composed: false;

})

After creating an event, they must be able to be dispatched to the site, and they can be sent to any object that can also be targeted by EventTarget. This means any HTML elements, the document, and even the window itself can have custom events sent to it.

document.querySelector("#idOfElement").dispatchEvent(newEvent);

From there, you can set up an event listener to listen for the event, and then build functions for the triggering of that event.

document.querySelector("#idOfElement").addEventListener("newEvent", (event) => {

console.log("I'm listening to my custom event");

});

Why do others use custom events?

As stated before, custom events allow developers to create their own events that aren't present within the DOM's API naturally. In addition, they allow the developer to create events and have them be reusable and intuitive for others to understand. More practical use-case scenarios of custom events include the use of custom UI components, communication of data between components, and for the integration of third-party apps and services.

Conclusion

Custom events are a type of event in JavaScript that allows developers to customize them to detect specific events, and run their own functions. Custom events are used quite commonly, and allow for the creation of custom UIs and integration of third-party apps and services on a website.

Sources

Custom Events in JavaScript: A Complete Guide- LogRocket

...

Custom Events in JavaScript- Devlane