How to trigger event in JavaScript?

  1. Home
  2. javascript
  3. 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?

First answer

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 created

if (document.createEvent) {
  event = document.createEvent("HTMLEvents");
  event.initEvent("dataavailable", true, true);
} else {
  event = document.createEventObject();
  event.eventType = "dataavailable";
}

event.eventName = "dataavailable";

if (document.createEvent) {
  element.dispatchEvent(event);
} else {
  element.fireEvent("on" + event.eventType, event);
}

Second answer

if you use jQuery, you can simple do

$('#yourElement').trigger('customEventName', [arg0, arg1, ..., argN]);

and handle it with

$('#yourElement').on('customEventName',
   function (objectEvent, [arg0, arg1, ..., argN]){
       alert ("customEventName");
});

where “[arg0, arg1, …, argN]” means that these args are optional.

Third answer

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 });
Reprint:https://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript
Spread the love

Related articles

Comments are closed.