JavaScript Reference ยท DOM: Events
EventTarget.dispatchEvent() method
Reference for dispatchEvent(): fire built-in or custom events from code, understand synchronous delivery, bubbling, the return value and untrusted events.
The dispatchEvent() method sends an event object to a target, so that all matching listeners run. You create the event yourself, with new Event(), new CustomEvent() or a more specific constructor such as new MouseEvent(), and then dispatch it.
Dispatching is synchronous: every listener has finished before dispatchEvent() returns. The return value tells you whether any listener called preventDefault() on a cancelable event.
const allowed = target.dispatchEvent(event);
Try it
Syntax
dispatchEvent(event)
Parameters
| Name | Description |
|---|---|
event |
An Event object (or a subclass). It must not be currently dispatching, and it must be initialized. |
Return value
A boolean. It is false if the event is cancelable and at least one listener called preventDefault(). Otherwise it is true. A non-cancelable event always gives true.
Exceptions
InvalidStateError(DOMException) if the event is already being dispatched. You can re-dispatch the same event object after the first dispatch has finished.TypeErrorif the argument is not anEvent.
Usage notes
- Bubbling must be requested. Events you create default to
bubbles: falseandcancelable: false. Pass{ bubbles: true }if ancestors should hear the event, and{ cancelable: true }if listeners may cancel it. - Synchronous. Code after the call runs only after all listeners finished. Errors thrown in listeners are reported but do not reach your
dispatchEvent()call. - Untrusted events.
event.isTrustedisfalsefor dispatched events. Listeners run as usual, but the browser does not perform most default actions for them: a synthetickeydowndoes not type a character into a field, and a syntheticmousedowndoes not start a text selection. - Use the right method for actions. For a button or checkbox, call
element.click()instead of dispatching aMouseEvent. It also triggers the real default action. - Custom data. Use
CustomEventand itsdetailproperty to carry data with the event. - Any
EventTargetworks. You can build your own event bus withnew EventTarget()and dispatch to it, without involving the DOM. - Event names. Use a distinct, lowercase or kebab-case name for custom events (
cart-updated) to avoid collisions with built-in ones.
Browser support
dispatchEvent() and the Event constructor work in all current browsers. new EventTarget() as a standalone object is also supported in current browsers; check a compatibility table for older ones.
Related
CustomEventโ events that carry dataEventTarget.addEventListener()โ listen for eventsEvent.preventDefault()โ cancel an event- Lesson: Events