custom event js code example

Example 1: javascript custom events with data

//Listen for the event
window.addEventListener("MyEventType", function(evt) {
    alert(evt.detail);
}, false);

//Dispatch an event
var evt = new CustomEvent("MyEventType", {detail: "Any Object Here"});
window.dispatchEvent(evt);

Example 2: trigger event javascript

// Simple trigger event
document.querySelector(theElem).dispatchEvent(new Event('mouseover'))

Example 3: custom event js

const eventDetails = {
  'id': elemId
}
document.dispatchEvent (
  new CustomEvent('myCustomEvent', {'detail': eventDetails})
)

Tags:

Misc Example