Last active
August 29, 2015 14:03
-
-
Save ruthenium/9fa357d4d443db667513 to your computer and use it in GitHub Desktop.
Send event in pure js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// from: | |
// http://stackoverflow.com/a/2490876 | |
// https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent | |
// prototype.js | |
// https://gist.github.com/heyi/a76167229038b4718a50 | |
// and etc | |
(function(){ | |
var sendEvent = document.createEvent ? function(name, target) { | |
/* WARNING: | |
document.createEvent is deprecated (see the link to the mozilla dev above). | |
We must further use document.Event or document.CustomEvent | |
*/ | |
var event = document.createEvent("HTMLEvents"); | |
event.initEvent(name, true, true); // TODO: this should be customizeable | |
event.eventName = name; | |
return target.dispatchEvent(event); | |
} : function(name, target) { // IE < 9 | |
var event = document.createEventObject(); | |
event.eventType = event.eventName = name; | |
return target.fireEvent("on" + name, event); | |
/* NOTE: the line above can't trigger any custom event. | |
Only html events like mouse click and etc are allowed. | |
For custom events we should use smth like this: | |
if (!htmlEvents["on" + name]) target[name] ? target[name]() : target["on"+name](); | |
*/ | |
}; | |
// usage: | |
var someDiv = document.getElementById('foo'); | |
sendEvent('click', someDiv); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment