Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Custom Events in JavaScript

Posted in Javascript, javascript interview questions

Custom-events

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

 window.dispatchEvent(myDialogEvent);

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) {
        alert(event.detail.desc);
    }
});

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.