← Lessons

quiz vs the machine

Silver1090

Frontend

Custom Events

Dispatch your own DOM events to decouple components without a shared parent.

4 min read · intro · beat Silver to climb

Making your own events

The browser fires built in events like click and input, but you can also create and dispatch your own using the CustomEvent constructor and the dispatchEvent method.

A custom event carries a payload in its detail property, so listeners receive structured data rather than guessing from the DOM.

  • Create it: new CustomEvent named cart updated with a detail object.
  • Dispatch it: call dispatchEvent on any element.
  • Listen for it: addEventListener with the same name, then read event detail.

Bubbling and composition

By default custom events do not bubble. Set the bubbles option to true so ancestors can hear them through delegation. Inside web components, also set composed true to let the event cross shadow DOM boundaries.

When to use them

  • Loose coupling: a child signals upward without the parent passing callbacks down through many layers.
  • Framework boundaries: a vanilla widget can notify a React or Vue host using a plain DOM event.

Custom events turn the DOM itself into a lightweight message bus.

Key idea

CustomEvent plus dispatchEvent let components communicate through the DOM, carrying data in detail and opting into bubbling.

Check yourself

Answer to earn rating on the learn ladder.

1. Where does a custom event carry its payload?

2. By default, do custom events bubble?