Skip to content

Custom Events in JavaScript


In JavaScript, there are number of built in events like click, mouseover, submit, scroll etc. There are some drawbacks with these built in browser events. They works only with DOM elements.

Here is an example of click event:

document.addEventListener('click', function(event) {
    alert('Button Clicked');

Above code works with DOM element such as div, button, anchor tag where click event is attached. This is useful when you want a user to perform some action on your web page.
But you can create your custom events in JavaScript. JavaScript provides a way to create and dispatch a custom events as shown below.

var myDialogEvent = new CustomEvent("showDialog", {
    cancelable: true,
    detail: {
          desc: "Display alert message with custom text",
          time: new Date(),

Create a CustomEvent object and pass the details about the events. However, detail and cancelable parameters are optional. You can pass empty object to the newly created custom event object.

var myDialogEvent = new CustomEvent("showDialog", {});

cancelable: true means events can be cancelled using event.stopPropagation.
In the detail you can mentioned some description about the event.

Dispatch Event

You can dispatch the event using window.dispatchEvent


The ‘myDialogEvent’ gets triggered once you dispatch it. It’s time to create a listener for your custom event. Listening for a custom event you just created is similar to adding a listener for DOM events.

window.addEventListener('showDialog', function(event) {
    if (event.detail) {

Once the event is triggered above code handle the ‘showDialog’ event and display an alert with the event description.

Use custom events if you are creating any JavaScript library or framework for your projects. If you have used any JavaScript framework like React or Angular with JQuery it custom events would be a good choice for communicating any Angular or React component with JQuery code.

Published inJavascriptjavascript interview questions

Be First to Comment

Leave a Reply

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