Event

Term side of the Card.
Topic: Event
Unit title: Event
Categories: Object
Explanation side of the Card

Explanation: The browser API object that represents an action or occurrence, such as user interactions or browser events, which can be detected and handled in the code. It includes details about the event, such as the type and target element.

Browser compatibility:
  • The chrome browser supports this feature starting from version 1.
  • The edge browser supports this feature starting from version 12.
  • The firefox browser supports this feature starting from version 1.
  • The safari browser supports this feature starting from version 1.
Availability: 

Example

Wrongjs
const evt = new Event('cart:update');
button.dispatchEvent(evt);
document.addEventListener('cart:update', render);
Rightjs
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 document listener because bubbles was left false.
  • Using window.event instead of the handler's event parameter.

Key points

  • Custom events use new CustomEvent('name', { detail }), not the legacy document.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.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy