Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท DOM: Events

The CustomEvent interface

Reference for CustomEvent: build your own named events, attach data with detail, make them bubble and cancelable, and dispatch them on elements or an EventTarget.

CustomEvent is an Event subclass for events you define yourself. Its one extra feature is the detail property, which can hold any value: a number, a string, an object or null. Listeners read it as event.detail.

Custom events let separate parts of a page talk to each other without direct references. A component dispatches "cart-updated", and anything interested listens for it.

JavaScript
const event = new CustomEvent("cart-updated", {
  detail: { items: 3 },
  bubbles: true
});
element.dispatchEvent(event);

Try it

A custom event with data
JS An event bus without the DOM

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
new CustomEvent(type)
new CustomEvent(type, options)

Parameters

Name Description
type A string naming the event. It can be any string, for example "cart-updated".
options.detail Any value to pass to listeners. Defaults to null.
options.bubbles Boolean. If true, the event travels up through ancestors. Default false.
options.cancelable Boolean. If true, preventDefault() has an effect and dispatchEvent() can return false. Default false.
options.composed Boolean. If true, the event can cross a shadow DOM boundary. Default false.

Properties

  • detail โ€“ the value you passed (read-only).
  • All Event properties: type, target, currentTarget, bubbles, cancelable, defaultPrevented, isTrusted and so on.

Usage notes

  • Remember bubbles: true. By default a custom event reaches only listeners on the element you dispatched it on. Delegated listeners on ancestors need bubbling.
  • detail is shared, not copied. If you pass an object, all listeners see the same object, and a mutation by one is visible to the others. Use structuredClone() or Object.freeze() if that matters.
  • Naming. Pick names that cannot clash with built-in events. Many projects use a prefix or a hyphenated name such as app:ready or cart-updated.
  • Synchronous delivery. Listeners run during dispatchEvent(), before the next line of your code.
  • Not trusted. event.isTrusted is false for events created in script.
  • Subclassing. You can write class MyEvent extends CustomEvent or even extends Event with your own fields when you want named properties instead of detail.
  • Works on EventTarget. In current browsers you can create plain new EventTarget() objects and use them as a tiny event emitter.

Browser support

CustomEvent is supported in all current browsers. Constructing a bare EventTarget is also supported in current browsers; check a compatibility table if you target older ones.