CustomEvent()
The CustomEvent() constructor creates a new CustomEvent.
Syntax
CustomEvent(typeArg);
CustomEvent(typeArg, options);
Parameters
typeArg-
A string representing the name of the event.
optionsOptional-
An object, with the following properties:
-
"detail", optional and defaulting tonull, of any type, containing an event-dependent value associated with the event. This is available to the handler using theCustomEvent.detailproperty. - Any properties that can be used in the init object of the
Event()constructor.
-
Example
// create custom events
const catFound = new CustomEvent('animalfound', {
detail: {
name: 'cat'
}
});
const dogFound = new CustomEvent('animalfound', {
detail: {
name: 'dog'
}
});
// add an appropriate event listener
obj.addEventListener('animalfound', (e) => console.log(e.detail.name));
// dispatch the events
obj.dispatchEvent(catFound);
obj.dispatchEvent(dogFound);
// "cat" and "dog" logged in the console
Additional examples can be found at Creating and triggering events.
Specifications
| Specification |
|---|
| DOM Standard # ref-for-dom-customevent-customevent |
Browser compatibility
BCD tables only load in the browser