DOM Custom Events

What are DOM Custom Events?

Events allows the browser to signal that an action has occurred, whether user-directed (such as a click, mouse-over, or scroll) or as an automatic process in the browser (such as a page finishing loading or encountering an error). DOM events include click, contextmenu (triggered by a right-click on an element), mouseover/mouseout (mouse cursor hovers over/leaves an element), keydown/keyup (keyboard key is pressed and released), focus (a form element is in focus), and many others. DOM custom events (also known as "synthetic events") allow for the creation of events that are triggered by the script, rather than events fired by the browser.

How to Create Custom Events

DOM custom events may be created using the Event() or CustomEvent() constructor, which creates a new custom event object. The event constructor has a few parameters, the first one being type, which sets the event type (click, scroll, etc.). The second is options, which contains bubbles (a boolean value that determines whether or not the event bubbles up to the root element) and cancelable (which determines whether or not the default action of the event can occur). There are two main parameters included in the custom event constructor, the first one being type, which provides the name of the event. The second parameter is options, which contains the detail parameter. These are optional, but may be used to set an event-dependent value. Custom events must also use addEventListener() to "listen" for the event. Finally, custom events are dispatched using dispatchEvent, which triggers the event to run when it is applied to a target.

Why are DOM Custom Events used?

DOM custom events are often used for events created for specific purposes, such as clicking a collapsable menu, or to account for certain events for which there are no built-in event handlers. Using custom events allows for code to be more manageable and reusable, as custom events can be called repeatedly once they have been defined.

Summary

DOM custom events allow for the creation of events outside the parameters of default events, and allow for more complex functions to be carried out upon a specific event occurring. Custom events are useful in the implementation of interactive features on a web page and lead to more reusable, manageable scripts. The custom event constructor allows for custom details to be passed along during the event's firing. Custom events can also change the default behavior of an element and allow programmers to set more complex or specific functions to be carried out instead.

Sources: