Event handling is a very important when it comes to making interactive websites. We can listen for various events on a element like click, mouse enter, mouse leave, key up etc. But sometimes these are not enough. Which is why many modern frameworks like Vue.js allows you to dispatch custom event and listen to them.
In this article we are going to see:
How to use custom events in Vanilla JavaScript
To create a custom event in JS we use CustomEvent
class
const options = {
detail: {
message: "Hello World!"
},
bubbles: true,
cancelable: true
}
const event = new CustomEvent(
"myEvent",
options
)
In this example, myEvent
is the custom event type. The second parameter is the config object(optional) with three properties:
-
detail: if you want to pass some data to the listeners of this event you can put them in this
detail
object. - bubbles: if true, events will bubble to ancestors of the element which fired the event.
- cancelable: if true, events can be canceled using the event object’s stopPropagation() method.
Okay so now use can use this event with document.addEventListener
and document.dispatchEvent
.
const options = {
detail: {
message: "Hello World!"
},
bubbles: true,
cancelable: true
}
const event = new CustomEvent(
"myEvent",
options
)
document.addEventListener("myEvent", e => console.log(e.detail))
//You can fire the event whenever you want
document.dispatchEvent(event)
Be sure to check out my other articles as well.