CustomEvent
Creates a new CustomEvent that can carry custom data via the detail property
Syntax
new CustomEvent(type, options?)Parameters
| Parameter | Type | Description |
|---|---|---|
| type | string | The name of the event |
| options | CustomEventInit | Options including detail, bubbles, cancelable, composed |
Return Value
A new CustomEvent object
Examples
const event = new CustomEvent('notification', {
detail: { message: 'Hello', type: 'info' }
})
document.dispatchEvent(event)document.addEventListener('app:theme-change', ((e: CustomEvent) => {
console.log('Theme changed to:', e.detail.theme)
}) as EventListener)
const event = new CustomEvent('app:theme-change', {
detail: { theme: 'dark' }
})
document.dispatchEvent(event)function createEventBus() {
const target = new EventTarget()
return {
on: (name: string, fn: (data: unknown) => void) =>
target.addEventListener(name, ((e: CustomEvent) => fn(e.detail)) as EventListener),
emit: (name: string, data: unknown) =>
target.dispatchEvent(new CustomEvent(name, { detail: data }))
}
}Understanding CustomEvent
The CustomEvent method in JavaScript creates a new CustomEvent that can carry custom data via the detail property. It belongs to the Event object and is one of the most widely used methods for working with event values in modern JavaScript and TypeScript applications.
The method signature is new CustomEvent(type, options?). It accepts 2 parameters: type, options. When called, it returns a new customevent object. Understanding when and how to use CustomEvent() helps you write more expressive, readable code.
Common use cases for CustomEvent include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like event-dispatchevent, event-addeventlistener, event-event-constructor, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for CustomEvent is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
EventTarget.prototype.dispatchEventDispatches an event to this EventTarget, invoking the affected event listeners in the appropriate order
EventTarget.prototype.addEventListenerRegisters an event handler of a specific event type on the EventTarget
EventCreates a new Event object that can be dispatched to an EventTarget
More Event Methods
Other methods in the Event object
Related Tools
More Event Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.