DEV Community

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

Posted on

5 1

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (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

Man you are a saviour
Thanks updated

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay