KoolKabin KoolKabin - 7 months ago 35
Javascript Question

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?

Answer

You can use fireEvent on IE, 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);
  }