Event
Example
const evt = new Event('cart:update');
button.dispatchEvent(evt);
document.addEventListener('cart:update', render);document.addEventListener('cart:update', (e) => render(e.detail));
const evt = new CustomEvent('cart:update', {
bubbles: true,
detail: { count: 3 }
});
button.dispatchEvent(evt);Events don't bubble by default, so set bubbles: true to reach document, pass data in detail, and listen before dispatching.
Common mistakes
- A custom event never reaches the
documentlistener becausebubbleswas left false. - Using
window.eventinstead of the handler's event parameter.
Key points
- Custom events use
new CustomEvent('name', { detail }), not the legacydocument.createEvent(). - Events meant to reach parent listeners are created with
bubbles: true, since it defaults to false. - Handlers read the event from the listener parameter, not the global
window.event.
Interview questions
Event vs CustomEvent: what is the difference?
CustomEvent extends Event with a detail property for passing data. Use it for your own events that carry a payload.
What does the third argument of addEventListener() do?
It is either a boolean for capture or an options object with capture, once, passive and signal.