How to create custom events in JavaScript

JavaScript events are actions or occurrences that happen on a web page. For example, clicking a button, typing in a form, or scrolling down a page, are all events. In JavaScript, we can create functions to respond to these events. This allows us to create interactive and dynamic web pages that respond to user input.

There are many predefined events present in JavaScript for us to use, but we also have the option to create our own custom events. This is really helpful when we want to setup communication between codes sitting in different parts of the application.

The Event() constructor

The Event() constructor creates a new event with the provided event name.

const event = new Event('my-event');

We can also customize our event by passing an options argument to the Event() constructor. The options object can have the following properties.

  • bubbles – set whether the event bubbles or not. The default is false.
  • cancelable – set whether the event can be cancelled or not. The default is false.
  • compose – set whether the event propagates outside the shadow root or not. The default is false.
const myEvent = new Event('my-event', {
  bubbles: true,
  cancelable: true
});

Now, like every other events, we can attach a listener function to this custom event which will execute when this event fires.

document.addEventListener('my-event', () => {
  console.log('my-event has fired');
});

As this is a custom event, the browser cannot fire it by itself; instead, we need to trigger it with the dispatchEvent method. Every element has access to this method.

document.dispatchEvent(myEvent);

Once we dispatch the custom event, every listener that is listening to this custom event will execute.

Creating custom events with the Event() constructor has a limitation that we cannot pass any custom data in the event. For this use case, we can use the CustomEvent() constructor to create events.

The CustomEvent() constructor

The CustomEvent() constructor is exactly the same as the Event() constructor, but it lets us pass an additional property named detail in the options object, which is used for passing custom data.

const messageEvent = new CustomEvent('message', {
  bubbles: true,
  cancelable: true,
  detail: {
    message: 'Hello world',
    sender: 'Han Solo'
  }
});

We can access this detail property on the event object inside the listener function.

document.addEventListener('message', (e) => {
  const { message, sender } = e.detail;
  console.log(`message received from ${sender}: ${message}`);
  // message received from Han Solo: Hello world
});

We can pass data of any type in the detail property; it doesn’t need to be an object always.

new CustomEvent('event-1', { detail: 'Hello' });
new CustomEvent('event-2', { detail: ['x', 'y', 'z'] });
new CustomEvent('event-3', { detail: 100 });
new CustomEvent('event-4', { detail: true });

Leave a Reply

Your email address will not be published. Required fields are marked *