Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Custom Events in JavaScript

Create and dispatch custom events in JavaScript with CustomEvent, detail data, bubbles and dispatchEvent. Simple explanation, use cases and the output.

IntermediateJavaScript Events ProgramsExample 2 of 10

This code needs a web page. Add the HTML elements it looks up by id, link the script, and open the page in a browser. Node has no document object. Add <button id="myButton">Save</button> to the page.

custom-events.js
1// Method 1: Create custom event
2const customEvent = new CustomEvent('myCustomEvent', {
3 detail: { message: 'Hello from custom event', data: 123 },
4 bubbles: true,
5 cancelable: true
6});
7
8// Listen for custom event
9document.addEventListener('myCustomEvent', function(event) {
10 console.log('Custom event received:', event.detail);
11 console.log('Message:', event.detail.message);
12 console.log('Data:', event.detail.data);
13});
14
15// Dispatch custom event
16document.dispatchEvent(customEvent);
17
18// Method 2: Custom event on specific element
19const button = document.getElementById('myButton');
20
21button.addEventListener('buttonClicked', function(e) {
22 console.log('Button custom event:', e.detail);
23});
24
25const buttonEvent = new CustomEvent('buttonClicked', {
26 detail: { buttonId: 'myButton', timestamp: Date.now() }
27});
28
29button.dispatchEvent(buttonEvent);
30
31// Method 3: Event with data
32const dataEvent = new CustomEvent('dataUpdate', {
33 detail: {
34 userId: 123,
35 action: 'update',
36 payload: { name: 'John', age: 30 }
37 }
38});
39
40document.addEventListener('dataUpdate', function(e) {
41 console.log('User ID:', e.detail.userId);
42 console.log('Action:', e.detail.action);
43 console.log('Payload:', e.detail.payload);
44});
45
46document.dispatchEvent(dataEvent);
47
48// Method 4: Event with validation
49function createValidatedEvent(type, data) {
50 if (!data || typeof data !== 'object') {
51 throw new Error('Data must be an object');
52 }
53
54 return new CustomEvent(type, {
55 detail: data,
56 bubbles: true,
57 cancelable: true
58 });
59}
60
61const validatedEvent = createValidatedEvent('validated', { value: 42 });
62document.dispatchEvent(validatedEvent);

Sample Output

Button custom event: { buttonId: ... }

The timestamp comes from Date.now(), so your number will differ.

Payload: { name: 'John', age: 30 }

The validated event at the end has no listener, so it prints nothing.

In this one

  • How to build a CustomEvent with detail data
  • What bubbles and cancelable do
  • Why a listener must exist before dispatch
  • How custom events decouple parts of a page

How it works

  1. 1

    myCustomEvent is created with a message and data.

  2. 2

    A document listener prints the detail, then the event is dispatched.

  3. 3

    A buttonClicked event is sent on the button.

  4. 4

    A dataUpdate event prints userId, action and payload.

  5. 5

    createValidatedEvent checks the data and dispatches a validated event.

Edge cases

Dispatching before listening

Nothing prints.

dispatchEvent runs listeners at that moment. Add listeners first.

Event does not reach the parent

A listener on document never fires for an element event.

Set bubbles: true so it travels up the DOM.

Wrong data type

createValidatedEvent('x', 'text') throws.

The helper only accepts objects. Pass { value: "text" } instead.

What's going on

The browser has built-in events like click. A custom event is one you invent and name yourself, like "marksUpdated". Custom events let different parts of a page talk to each other without calling each other directly. That is called loose coupling. One part announces "this happened" and any part that cares can listen.

You create one with new CustomEvent(name, options). The options object has four useful fields. type is the event name you pass first. detail holds your own data, such as { message, data }. bubbles: true lets the event travel up the DOM to parent elements. cancelable: true lets a listener call preventDefault() on it.

Method 1 creates myCustomEvent, adds a listener on document, and then calls document.dispatchEvent. Dispatch means "send out now". The listener reads event.detail to get the message and the number.

Order matters here. The listener must be added before you dispatch. dispatchEvent runs listeners right away, in the same moment. A listener added later will miss the event.

Method 2 sends a buttonClicked event on one button element, with the button id and a timestamp. Method 3 sends a dataUpdate event with a user id, an action, and a payload object, like a profile update.

Method 4 wraps creation in a helper that throws an error if the data is not an object. That keeps every event in the same shape.

Use cases include communication between components, a decoupled architecture, custom notifications, and plugin systems. The benefits are loose coupling, reusable components, better organisation, and an event-driven design.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Where do you put your own data in a CustomEvent?

Pick an answer to check it.

Question 2

What makes a custom event travel to parent elements?

Pick an answer to check it.

Questions people ask

Is dispatchEvent asynchronous?

No. Listeners run before dispatchEvent returns.

Why use detail?

It is the standard place for your own data on a CustomEvent.

Can I use custom events in Node?

Node 19+ has CustomEvent and EventTarget, but no document.