Path: blob/main/files/en-us/web/events/creating_and_triggering_events/index.md
6580 views
------This article demonstrates how to create and dispatch DOM events. Such events are commonly called synthetic events, as opposed to the events fired by the browser itself.
Creating custom events
Events can be created with the Event constructor as follows:
The above code example uses the EventTarget.dispatchEvent() method.
This constructor is supported in most modern browsers. For a more verbose approach, see the old-fashioned way below.
Adding custom data – CustomEvent()
To add more data to the event object, the CustomEvent interface exists and the detail property can be used to pass custom data. For example, the event could be created as follows:
This will then allow you to access the additional data in the event listener:
The old-fashioned way
The older approach to creating events uses APIs inspired by Java. The following shows an example with {{domxref("document.createEvent()")}}:
Event bubbling
It is often desirable to trigger an event from a child element, and have an ancestor catch it; optionally, with data:
Creating and dispatching events dynamically
Elements can listen for events that haven't been created yet:
Triggering built-in events
This example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using DOM methods. View the example in action.
See also
{{domxref("document.createEvent()")}}
{{domxref("Event.initEvent()")}}
{{domxref("EventTarget.dispatchEvent()")}}
{{domxref("EventTarget.addEventListener()")}}