Skip to content
Related Articles

Related Articles

JavaScript Custom Events
  • Last Updated : 05 Mar, 2021

Events are used in almost every web application, such as the onclick event being used to execute some code when the user clicks on something. There are already numerous built-in events available to be used, but what if we want our own custom event? Let us suppose we are creating a chat application, and we want to execute some code when the end-user sends some message. There is no built-in event to detect that. Here we need a custom event that can handle such custom scenarios.

Creating a Custom Event: To create a custom event we use the Event constructor or CustomEvent interface. The Event constructor creates an Event and CustomEvent creates an Event with more functionality.

The below steps are followed in order to create one using a new Event.

  • We create an event using the Event constructor.
  • We listen to this event using the addEventListener() method.
  • We trigger or dispatch the event using element.dispatchEvent(eventName) method.
  • A custom Event named start has now been created.

Syntax:

// To assign event
const event = new Event("start");

// To trigger the event Listner
document.addEventListener("start", () => {
    console.log("The start event was triggered")
});

// To trigger the Event
document.dispatchEvent("start");

Example: In this example, we are creating an event that is triggered when the value of x is 5.



HTML




<html
<body>
  <script>
    let x = 5;
    const event = new Event("start");
      
    document.addEventListener('start', ()=>{
      console.log("Start event triggered")
    });
      
    if(x == 5){
      document.dispatchEvent(event);
    }
  </script>
</body>
</html>

Output:

"Start event triggered"

Creating a custom event using CustomEvent: Creating custom events using the CustomEvent interface has an advantage as it can send custom data. The below steps are followed in order to create a new CustomEvent.

  • We create a custom event using the CustomEvent constructor.
  • This takes two arguments, the first is the name of the event and the second is an object that contains the data. The property name inside the object name should be named detail otherwise it won’t work.
  • We create a listener for this event.
  • We trigger or dispatch the event.
  • A custom event that contains data has been created.

Syntax:

// To assign event
const event = new CustomEvent("start", {
      detail: {
        platform : "GeeksforGeeks"
      }
});

// To trigger the event Listner
document.addEventListener('start', (e)=>{
      console.log(
        `start event triggered on platform :
        ${e.detail.platform}`
        );
});

// To trigger the Event
document.dispatchEvent(event);

Example 2: In this example, we are creating a custom event that triggers when the value of x is 5.

HTML




<html>  
<body>
  <script>
    let x = 5;
     const event = new CustomEvent("start", {
      detail: {
        platform : "GeeksforGeeks"
      }
    });
      
    document.addEventListener('start', (e) => {
      console.log(
        `Start event triggered on platform 
        ${e.detail.platform}`
      );
    })
      
    if (x == 5) {
      document.dispatchEvent(event);
    }
  </script>
</body>
</html>

Output:

Start event triggered on platform GeeksforGeeks

Note: We are dispatching the event directly from the document using document.dispatchEvent(‘start’), but one can dispatch the event from any needed element like myBtn.dispatchEvent(‘start’).

My Personal Notes arrow_drop_up
Recommended Articles
Page :