Creating and triggering events
Creating and triggering events
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:
1 | const event = new Event('build'); |
The above code example uses the EventTarget.dispatchEvent()
method.
This constructor is supported in most modern browsers (with Internet Explorer being the exception). For a more verbose approach (which works with Internet Explorer), 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:
1 | const event = new CustomEvent('build', { detail: elem.dataset.time }); |
This will then allow you to access the additional data in the event listener:
1 | function eventHandler(e) { |
The old-fashioned way
The older approach to creating events uses APIs inspired by Java. The following shows an example with document.createEvent()
:
1 | // Create the event. |
Event bubbling
It is often desirable to trigger an event from a child element, and have an ancestor catch it; optionally, with data:
1 | <form> |
1 | const form = document.querySelector('form'); |
Creating and dispatching events dynamically
Elements can listen for events that haven’t been created yet:
1 | <form> |
1 | const form = document.querySelector('form'); |
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.
1 | function simulateClick() { |
EventTarget.dispatchEvent(event)返回值:当该事件是可取消的(cancelable为true)并且至少一个该事件的事件处理方法调用了Event.preventDefault(),则返回值为false;否则返回true。