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.
const event = new CustomEvent("cart-updated", { detail: { items: 3 }, bubbles: true }); element.dispatchEvent(event);
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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
Eventproperties:type,target,currentTarget,bubbles,cancelable,defaultPrevented,isTrustedand 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. detailis shared, not copied. If you pass an object, all listeners see the same object, and a mutation by one is visible to the others. UsestructuredClone()orObject.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:readyorcart-updated. - Synchronous delivery. Listeners run during
dispatchEvent(), before the next line of your code. - Not trusted.
event.isTrustedisfalsefor events created in script. - Subclassing. You can write
class MyEvent extends CustomEventor evenextends Eventwith your own fields when you want named properties instead ofdetail. - Works on
EventTarget. In current browsers you can create plainnew 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.
Related
EventTarget.dispatchEvent()โ send the eventEventTarget.addEventListener()โ receive the event- event bubbling and capturing โ how
bubblesworks - Lesson: Events