Skip to content

Instantly share code, notes, and snippets.

@dciccale
Last active May 22, 2018 09:14
Show Gist options
  • Save dciccale/6226151 to your computer and use it in GitHub Desktop.
Save dciccale/6226151 to your computer and use it in GitHub Desktop.
Cross-browser triggerEvent function done with 127 bytes of JavaScript

triggerEvent

Cross-browser function to trigger DOM events.

<!doctype html>
<title>Demo</title>
<span id="btn">Button</span>
<script>
// use addEvent cross-browser shim: https://gist.github.com/dciccale/5394590/
var addEvent = function(a,b,c){try{a.addEventListener(b,c,!1)}catch(d){a.attachEvent('on'+b,c)}};
// triggerEvent
var triggerEvent = function(c,d,b,a){b=document;b.createEvent?(a=new Event(d),c.dispatchEvent(a)):(a=b.createEventObject(),c.fireEvent("on"+d,a))};
// DOM element
var element = document.getElementById('btn');
// callback function
var callback = function () { alert('Button clicked!'); };
addEvent(element, 'click', callback);
// alert 'Button clicked!' when trigger click event
triggerEvent('click', element, callback);
</script>
/**
* @param target can be any DOM Element or other EventTarget
* @param type Event type (i.e. 'click')
* @param doc Placeholder for document
* @param event Placeholder for creating an Event
*/
function (target, type, doc, event) {
doc = document;
if (doc.createEvent) {
event = new Event(type);
target.dispatchEvent(event);
} else {
event = doc.createEventObject();
target.fireEvent('on' + type, event);
}
};
function(c,d,b,a){b=document;b.createEvent?(a=new Event(d),c.dispatchEvent(a)):(a=b.createEventObject(),c.fireEvent("on"+d,a))}
@Johnius
Copy link

Johnius commented Sep 5, 2016

triggerEvent in demo mismatched signature with actual implementation. First argument should be an element and second one is event.

@AndresSepar
Copy link

AndresSepar commented May 9, 2017

This fixes the error:
Uncaught TypeError: c.dispatchEvent is not a function

function(target, type, doc, event) {
    doc = document;
    if (doc.createEvent) {
      event = doc.createEvent('HTMLEvents');
      event.initEvent(type, true, true);
      target.dispatchEvent(event);
    } else {
      event = doc.createEventObject();
      target.fireEvent('on' + type, event);
    }
  };
function (a,b,c,d){c=document,c.createEvent?(d=c.createEvent("HTMLEvents"),d.initEvent(b,!0,!0),a.dispatchEvent(d)):(d=c.createEventObject(),a.fireEvent("on"+b,d))}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment