javascripteventstriggersaddeventlistenerdom-events

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?


Solution

  • Note: the initEvent method is now deprecated. Other answers feature up-to-date and recommended practice.


    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);
        event.eventName = "dataavailable";
        element.dispatchEvent(event);
    } else {
        event = document.createEventObject();
        event.eventName = "dataavailable";
        event.eventType = "dataavailable";
        element.fireEvent("on" + event.eventType, event);
    }