dom / latest / customevent / customevent.html /

CustomEvent()

The CustomEvent() constructor creates a new CustomEvent.

Syntax

CustomEvent(typeArg);
CustomEvent(typeArg, options);

Parameters

typeArg

A string representing the name of the event.

options Optional

An object, with the following properties:

  • "detail", optional and defaulting to null, of any type, containing an event-dependent value associated with the event. This is available to the handler using the CustomEvent.detail property.
  • 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

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
CustomEvent
15
12
11
No
11.6
6
4.4
18
14
12
6
1.0

See also

© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent