DEV Community

Cover image for Hey, there's a new CustomEvent() going
Shuvo
Shuvo

Posted on

Hey, there's a new CustomEvent() going

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
)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Custom event demo

Be sure to check out my other articles as well.

0shuvo0 image

Discussion (2)

Collapse
quasipickle profile image
Dylan Anderson

I don't know if you can edit these posts, but right after the "How to use custom events in Vanilla JavaScript" heading, you use CustomImage instead of CustomEvent.

Collapse
0shuvo0 profile image
Shuvo Author

Man you are a saviour
Thanks updated