Learn how to create, dispatch, and listen for custom events to build more interactive and decoupled web apps.
Master this powerful technique for cleaner, modular JavaScript!
You can dispatch custom events like so:
const myEvent = new CustomEvent("myevent", {
detail: {},
bubbles: true,
cancelable: true,
composed: false,
});
document.querySelector("#someElement").dispatchEvent(myEvent);
To listen for the custom event, add an event listener to the element you want to listen on, just as you would with native DOM events.
document.querySelector("#someElement").addEventListener("myevent", (event) => {
console.log("I'm listening on a custom event");
});
Read more 👉 blog.logrocket.com/custom-events-in-javascript-a-complete-guide/
Top comments (1)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.