How do you create and dispatch a custom DOM event?
Short 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.
Advertisement
AModel 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 42Real-world example
Decoupling a cart component from a header badge by having them communicate via a custom 'cartUpdated' event.
Likely follow-ups
- Does a custom event bubble by default?
Related topics