DOM Custom Events

What are DOM Custom Events?

Normal DOM Events are used extensively in JavaScript programming. From managing button clicks to listening for key-presses, DOM Events allow single-page web applications to truly come to life.

Custom events, on the other hand, allow you to create your own events that you call, as opposed to the browser. According to the MDN Web Docs, these events are sometimes referred to as synthetic events.

How can I create a DOM Custom Event?

According to the MDN Web Docs, creating a synthetic event is as simple as calling the event constructor.

const event = new Event('build');

We can then add an event listener to the event like usual, specifying the code to run in the event's second parameter.

elem.addEventListener('build', (e) => { /* … */ }, false);

Finally, when we wish to manually invoke the event, we can call the DOM's dispatchEvent method. According to the MDN Web Docs, this method can be called for any type of event, regardless of whether it is synthetic.

elem.dispatchEvent(event);

When would I need a DOM Custom Event?

Custom events may be useful in situations where custom business logic needs to be listened for underneath the scenes. For example, GeeksForGeeks, a source of programming-related documentation, recommended the use of custom events to listen for when a message is sent in a chat application. The browser will not dispatch this event by default, so it must be called in-code.

Summary

Although most of the events that we use in JavaScript are called automatically by the browser, sometimes we need to create synthetic events to implement custom business logic. We can then call these events manually by using the DOM's built-in dispatchEvent method.

For those who are interested in digging deeper, I recommend the MDN Web Docs as a good resource in this area. The documentation resource seems to be more-thorough than other resources and provides links to other aspects of the language.