How to trigger event in JavaScript?

870,412

Solution 1

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);
}

Solution 2

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.

Solution 3

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 }));

Solution 4

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.

Solution 5

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


If you are supporting IE9+ the you can use the following. The same concept is incorporated in You Might Not Need jQuery.

function addEventListener(el, eventName, handler) {
  if (el.addEventListener) {
    el.addEventListener(eventName, handler);
  } else {
    el.attachEvent('on' + eventName, function() {
      handler.call(el);
    });
  }
}

function triggerEvent(el, eventName, options) {
  var event;
  if (window.CustomEvent) {
    event = new CustomEvent(eventName, options);
  } else {
    event = document.createEvent('CustomEvent');
    event.initCustomEvent(eventName, true, true, options);
  }
  el.dispatchEvent(event);
}

// Add an event listener.
addEventListener(document, 'customChangeEvent', function(e) {
  document.body.innerHTML = e.detail;
});

// Trigger the event.
triggerEvent(document, 'customChangeEvent', {
  detail: 'Display on trigger...'
});

If you are already using jQuery, here is the jQuery version of the code above.

$(function() {
  // Add an event listener.
  $(document).on('customChangeEvent', function(e, opts) {
    $('body').html(opts.detail);
  });

  // Trigger the event.
  $(document).trigger('customChangeEvent', {
    detail: 'Display on trigger...'
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Share:
870,412
KoolKabin
Author by

KoolKabin

A freelance web developer Websites: 1.) http://biotechx.com 2.) http://highcountrytrekking.com 3.) http://firante.com 4.) http://himalayanencounters.com 5.) http://ajisai.edu.np 6.) http://environmentnepal.info/test 7.) http://treknepal.au 8.) http://sunshinetrekking.com 9.) http://taverntrove.com 10.) http://trekkingandtoursnepal.com 11.) http://outsourcingnepal.com

Updated on October 30, 2021

Comments

  • KoolKabin
    KoolKabin over 2 years

    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?

  • Rohan Desai
    Rohan Desai over 12 years
    Dont't forget that only the IE version has the 'on' in front (I missed that at first)
  • NeDark
    NeDark over 12 years
    What does the variable eventName contain here?
  • ThemeZ
    ThemeZ about 12 years
    @Alsciende how can I attach my event handler to this custom event?
  • alagar
    alagar over 11 years
    dataavailable should be in the eventName variable I believe.
  • Charles
    Charles almost 11 years
    Yep dataavailable should be in eventName and memo should be defined too (define to {} is ok).
  • B T
    B T over 10 years
    I think the question is: where does eventName come from? In this code it is undefined. Should it be "dataavailable"? If so, please edit the answer.
  • Blake
    Blake over 10 years
    Internet Explorer 9+ handles createEvent and dispatchEvent, so there is no need for those if statements.
  • Dorian
    Dorian over 10 years
    This example doesn't even works, see my answer: stackoverflow.com/a/20548330/407213
  • nicholaswmin
    nicholaswmin almost 10 years
    I am confused on whether this is a cross-browser technique. Is it?
  • Kiril
    Kiril almost 10 years
    This answer is more actual now. One thing to add: if there should be a know-typed event (like TransitionEvent, ClipboardEvent, etc) the appropriate constructor could be called.
  • harry
    harry almost 10 years
    The correct syntax is $('#yourElement').trigger('customEventName', [ arg0, arg1, ..., argN ]); You have forgotten the [] at the second parameter
  • georgelviv
    georgelviv about 9 years
    fireEvent on IE what verison of IE it supports?
  • Brendan
    Brendan over 8 years
    Looks like the process for creating custom events might change at some point - see the MDN article for more details. But for now this answer worked fine for me, so thanks!
  • Kamuran Sönecek
    Kamuran Sönecek over 8 years
    trigger method is not wrong, but it is a jquery method
  • Mardok
    Mardok over 8 years
    This does not take into account what kind of event it is. Blurring and focusing may trigger the event but it may not as well. This is inviting bugs.
  • Andreas Haufler
    Andreas Haufler about 8 years
    The last lines have to call document.dispatchEvent and document.fireEvent respectively.
  • Glenn Jorde
    Glenn Jorde about 8 years
    1. document.getElementByClassName doesn't exist. 2. document.getElementsByClassName exist but returns a list. 3. this only works for a select few native events. 4. The last example triggers a jQuery event where no underlying native event exists.
  • Ciro Santilli OurBigBook.com
    Ciro Santilli OurBigBook.com almost 8 years
    document.createEvent seems to be deprecated in favor of new Event: developer.mozilla.org/en-US/docs/Web/API/Document/createEven‌​t
  • Dorian
    Dorian almost 8 years
    @AngelPolitis: Because it was written after the previous one was already accepted and the person who wrote the question (@KoolKabin) probably didn't re-read the answers
  • ling
    ling over 7 years
    does not work on ie11 via virtualbox on mac host: github.com/lingtalfi/browsers-behaviours/blob/master/…
  • hipkiss
    hipkiss over 7 years
    This is deprecated. Only useful for polyfills. developer.mozilla.org/en-US/docs/Web/API/MouseEvent/…
  • AxeEffect
    AxeEffect almost 7 years
    This also applies to element.click().
  • SidOfc
    SidOfc almost 7 years
    This will not work for any version of IE, as a window.CustomEvent exists but it cannot be called as a constructor: caniuse.com/#search=CustomEvent ;)
  • SidOfc
    SidOfc almost 7 years
    What if you want to do multiple different things for the same event (or well, callback function in your case) depending on context? :) It's a good alternative but this feels more like a comment than an answer as the OP wants to know how to programmatically trigger an event as opposed to using a callback :)
  • DarkNeuron
    DarkNeuron almost 7 years
    And because it was asked in 2010
  • DarkNeuron
    DarkNeuron almost 7 years
    This fixed a weird issue for my Angular/Cordova app, in Android, where the textarea would refuse to clear itself. So thanks.
  • Andrew
    Andrew over 6 years
    or: $(selector).change();
  • KWallace
    KWallace over 6 years
    You are quite right that this should have been a comment rather than an answer. Why? Because, uhm, well, .... it doesn't answer the question that was actually asked. Good call. As to your own question, I'd say this would be a great opportunity for constructors in JavaScript! ;-) But without them, I'd say, send an argument with your function call and let that be used to determine what the function should do.
  • Yarin
    Yarin about 6 years
    Won't work with any version of IE (caniuse.com/#feat=customevent). See my answer for a fix.
  • user2912903
    user2912903 about 5 years
    This should be the accepted answer as it doesn't use deprecated methods like initEvent()
  • Fabian von Ellerts
    Fabian von Ellerts about 5 years
    Nice solution, but be aware this will not work on IE11. You should then use CustomEvent and the according polyfill.
  • daka
    daka about 4 years
    Note to future readers, detail is a property of the Event, so assign any data you want to access at the other end to it and access by event.detail. +1
  • vir us
    vir us almost 4 years
    in your comment "For modern browsers except IE" I guess "except IE" is redundant ;)
  • jak.b
    jak.b over 3 years
    @CiroSantilli郝海东冠状病六四事件法轮功 Document.createEvent() isn’t deprecated, but Event.initEvent() is, see MDN.