CustomEvent

Dispatches an application-defined event, carrying arbitrary data via .detail, decoupling the code that announces something from whatever reacts to it.

                element.dispatchEvent(new CustomEvent(type, { detail, bubbles }))
              

Purpose

CustomEvent lets application code define and dispatch its own events, following the exact same dispatchEvent/addEventListener mechanism as native browser events — decoupling the code that triggers something from whatever else reacts to it.

Syntax

const cart = document.querySelector('#cart');

cart.dispatchEvent(
  new CustomEvent('cart:item-added', {
    detail: { itemId: 42, quantity: 1 },
    bubbles: true,
  }),
);

document.addEventListener('cart:item-added', (event) => {
  console.log('Item added:', event.detail.itemId);
});

Behavior notes

  • event.detail carries arbitrary data along with the event — the equivalent of a native event’s built-in properties (event.target, and similar), but application-defined.
  • bubbles: true is required for the event to propagate up through ancestors the way native events do by default — without it, only a listener on the exact dispatching element receives it.
  • Namespacing custom event names (cart:item-added rather than just item-added) avoids collisions with native event names or other application code’s custom events.

Common mistakes

  • Forgetting bubbles: true and being surprised a listener higher up the tree never fires.
  • Using a custom event where a plain function call would be simpler and more direct — delegation via events adds indirection that’s worth its cost specifically when decoupling two genuinely independent pieces of code, not as a default communication mechanism for everything.

Runtime notes

Part of the DOM standard — browser-only.

Taught in these lessons

Related reference