Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
const allowed = target.dispatchEvent(event);

Try it

Dispatching a bubbling event
Cancelable events and the return value

Syntax

JavaScript
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.
  • TypeError if the argument is not an Event.

Usage notes

  • Bubbling must be requested. Events you create default to bubbles: false and cancelable: 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.isTrusted is false for dispatched events. Listeners run as usual, but the browser does not perform most default actions for them: a synthetic keydown does not type a character into a field, and a synthetic mousedown does not start a text selection.
  • Use the right method for actions. For a button or checkbox, call element.click() instead of dispatching a MouseEvent. It also triggers the real default action.
  • Custom data. Use CustomEvent and its detail property to carry data with the event.
  • Any EventTarget works. You can build your own event bus with new 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.