Back to results for “Design Patterns in Java”
JavaScript › DOM & Events

How do you create and dispatch a custom DOM event?

Intermediate

Answer

Construct a CustomEvent with an optional detail payload, then call dispatchEvent() on a target element; other code can listen for it exactly like a native event.
const event = new CustomEvent('itemAdded', { detail: { id: 42 } });
el.addEventListener('itemAdded', (e) => console.log(e.detail.id));
el.dispatchEvent(event); // logs 42
Real-world example Decoupling a cart component from a header badge by having them communicate via a custom 'cartUpdated' event.

Common follow-ups: Does a custom event bubble by default?