How to trigger event in JavaScript?
You can use fireEvent on IE 8 or lower, and W3C's dispatchEvent on most other browsers. To create the event you want to fire, you can use either createEvent
or createEventObject
depending on the browser.
Here is a self-explanatory piece of code (from prototype) that fires an event dataavailable
on an element
:
var event; // The custom event that will be createdif(document.createEvent){ event = document.createEvent("HTMLEvents"); event.initEvent("dataavailable", true, true); event.eventName = "dataavailable"; element.dispatchEvent(event);} else { event = document.createEventObject(); event.eventName = "dataavailable"; event.eventType = "dataavailable"; element.fireEvent("on" + event.eventType, event);}
A working example:
// Add an event listenerdocument.addEventListener("name-of-event", function(e) { console.log(e.detail); // Prints "Example of an event"});// Create the eventvar event = new CustomEvent("name-of-event", { "detail": "Example of an event" });// Dispatch/Trigger/Fire the eventdocument.dispatchEvent(event);
For older browsers polyfill and more complex examples, see MDN docs.
See support tables for EventTarget.dispatchEvent
and CustomEvent
.
If you don't want to use jQuery and aren't especially concerned about backwards compatibility, just use:
let element = document.getElementById(id);element.dispatchEvent(new Event("change")); // or whatever the event type might be
See the documentation here and here.
EDIT: Depending on your setup you might want to add bubbles: true
:
let element = document.getElementById(id);element.dispatchEvent(new Event('change', { 'bubbles': true }));