How to trigger event in JavaScript?

I have attached an event to a text box using addEventListener. It works fine. My problem arose when I wanted to trigger the event programmatically from another function.

How can I do it?

19 s
19

A working example:

// Add an event listener
document.addEventListener("name-of-event", function(e) {
  console.log(e.detail); // Prints "Example of an event"
});

// Create the event
var event = new CustomEvent("name-of-event", { "detail": "Example of an event" });

// Dispatch/Trigger/Fire the event
document.dispatchEvent(event);

For older browsers polyfill and more complex examples, see MDN docs.

See support tables for EventTarget.dispatchEvent and CustomEvent.

Leave a Comment