Skip to content

Instantly share code, notes, and snippets.

@kosinix
Created January 29, 2017 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kosinix/3a5d33432b248dc4ef59e98df34623e5 to your computer and use it in GitHub Desktop.
Save kosinix/3a5d33432b248dc4ef59e98df34623e5 to your computer and use it in GitHub Desktop.
Create custom event in plain JS. Supports modern browsers (IE11+)
// IE >= 11
function triggerEvent(el, eventName, options) {
var event,
opts = {detail: options};
event = newEvent(eventName, opts);
el.dispatchEvent(event);
}
function newEvent(eventName, options) {
var opts = {detail: options};
try { // catch IE 11
return new CustomEvent(eventName, opts); // Modern browsers be like..
} catch (e) {
var event = document.createEvent('CustomEvent'); // IE ruining the party..
event.initCustomEvent(eventName, true, true, opts);
return event;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment