How to Create and Dispatch Events in JavaScript?

Handling events in JavaScript is an important concept when creating applications. You might have used the ‘addEventListener‘ on events like ‘click‘, and ‘scroll‘. Ever thought of creating an event like these on your own? And then using it among multiple scripts throughout the DOM? Let’s go through the simple and short steps to create and dispatch custom events in JavaScript.

Create Events

Basic Event

We can create an event using the code snippet shown below.

let event_a = new Event("prompt_dialogue");

Custom Event

Sometimes you may need to pass important information as parameters by creating a Custom Event. This will hold information in the ‘detail‘ variable as shown below.

// var user_data= {first_name: "Scratch", last_name: "Coding"}
let event_b = new CustomEvent("sc_signin", {detail: {user_info: user_data}}); 

Here, the event name is ‘sc_signin‘ and the ‘detail‘ parameter holds ‘user_info‘ retrieved from the ‘user_data‘ variable.

However, to use an event in ‘addEventListener‘, we need to first dispatch the event.

Dispatch Event

We can dispatch an event to a div element or the entire document. Since this example discusses the case to use an event in an external script, we will dispatch events to the document object, as shown below.

document.dispatchEvent(event_a);
document.dispatchEvent(event_b);

Now you can use these events anywhere inside the document object on your web page.

Use Event

The code below automatically fires up once you create and dispatch your event.

document.addEventListener("sc_signin", function(event) {
   console.log(event.detail.user_info); // first_name: "Scratch", last_name: "Coding"
});

You can create custom events and use them when a specific operation occurs. This insures sequential flow of code and assures actions are performed and values are passed before they are used.

Conclusion

This approach helps create an efficient solution, especially when events and processes depend on each other. Suppose you need to read a value from ‘Script A’ where it is evaluated, you can create and dispatch an event there passing the value to it. Adding event listener to the same event, only reads the value once it is evaluated and the event is dispatched. Hope the tutorial helped you create and dispatch events on your own.