Open In App

JavaScript Custom Events

Events are used in almost every web application, such as the onclick event is 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 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 to create one using a new Event.

Syntax: 

// To assign event
const startEvent = new Event("start");
// To trigger the event Listener
document.addEventListener("start", () => {
console.log("The start event was triggered")
});
// To trigger the Event
document.dispatchEvent(startEvent);

Example: We are creating an event that is triggered when the value of x is 5.






<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.

Syntax: 

// To assign event
const event = new CustomEvent("start", {
detail: {
platform : "GeeksforGeeks"
}
});
// To trigger the event Listener
document.addEventListener('start', (e)=>{
console.log(
`start event triggered on platform :
${e.detail.platform}`
);
});
// To trigger the Event
document.dispatchEvent(event);

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




<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’).


Article Tags :