How to trigger event in JavaScript?
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>
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, 2021Comments
-
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 over 12 yearsDont't forget that only the IE version has the 'on' in front (I missed that at first)
-
NeDark over 12 yearsWhat does the variable
eventName
contain here? -
ThemeZ about 12 years@Alsciende how can I attach my event handler to this custom event?
-
alagar over 11 years
dataavailable
should be in theeventName
variable I believe. -
Charles almost 11 yearsYep dataavailable should be in eventName and memo should be defined too (define to {} is ok).
-
B T over 10 yearsI 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 over 10 yearsInternet Explorer 9+ handles createEvent and dispatchEvent, so there is no need for those if statements.
-
Dorian over 10 yearsThis example doesn't even works, see my answer: stackoverflow.com/a/20548330/407213
-
nicholaswmin almost 10 yearsI am confused on whether this is a cross-browser technique. Is it?
-
Kiril almost 10 yearsThis 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 almost 10 yearsThe correct syntax is $('#yourElement').trigger('customEventName', [ arg0, arg1, ..., argN ]); You have forgotten the [] at the second parameter
-
georgelviv about 9 yearsfireEvent on IE what verison of IE it supports?
-
Brendan over 8 yearsLooks 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 over 8 yearstrigger method is not wrong, but it is a jquery method
-
Mardok over 8 yearsThis 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 about 8 yearsThe last lines have to call
document.dispatchEvent
anddocument.fireEvent
respectively. -
Glenn Jorde about 8 years1.
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 almost 8 years
document.createEvent
seems to be deprecated in favor ofnew Event
: developer.mozilla.org/en-US/docs/Web/API/Document/createEvent -
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 over 7 yearsdoes not work on ie11 via virtualbox on mac host: github.com/lingtalfi/browsers-behaviours/blob/master/…
-
hipkiss over 7 yearsThis is deprecated. Only useful for polyfills. developer.mozilla.org/en-US/docs/Web/API/MouseEvent/…
-
AxeEffect almost 7 yearsThis also applies to
element.click()
. -
SidOfc almost 7 yearsThis 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 almost 7 yearsWhat 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 almost 7 yearsAnd because it was asked in 2010
-
DarkNeuron almost 7 yearsThis fixed a weird issue for my Angular/Cordova app, in Android, where the textarea would refuse to clear itself. So thanks.
-
Andrew over 6 yearsor: $(selector).change();
-
KWallace over 6 yearsYou 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 about 6 yearsWon't work with any version of IE (caniuse.com/#feat=customevent). See my answer for a fix.
-
user2912903 about 5 yearsThis should be the accepted answer as it doesn't use deprecated methods like initEvent()
-
Fabian von Ellerts about 5 yearsNice solution, but be aware this will not work on IE11. You should then use
CustomEvent
and the according polyfill. -
daka about 4 yearsNote to future readers,
detail
is a property of theEvent
, so assign any data you want to access at the other end to it and access byevent.detail
. +1 -
vir us almost 4 yearsin your comment "For modern browsers except IE" I guess "except IE" is redundant ;)
-
jak.b over 3 years@CiroSantilli郝海东冠状病六四事件法轮功 Document.createEvent() isn’t deprecated, but Event.initEvent() is, see MDN.