Skip to content

Instantly share code, notes, and snippets.

@vinaydotblog
Forked from JeffreyWay/gist:1946898
Created March 27, 2012 13:21
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 vinaydotblog/2215818 to your computer and use it in GitHub Desktop.
Save vinaydotblog/2215818 to your computer and use it in GitHub Desktop.
JS: Event listener for all browsers
// Event listener for all browsers
// Including some comments
var addEvent = (function () {
var filter = function(el, type, fn) {
for ( var i = 0, len = el.length; i < len; i++ ) {
addEvent(el[i], type, fn);
}
};
if ( document.addEventListener ) {
return function (el, type, fn) {
if ( el && el.nodeName || el === window ) {
el.addEventListener(type, fn, false);
} else if (el && el.length) {
filter(el, type, fn);
}
};
}
return function (el, type, fn) {
if ( el && el.nodeName || el === window ) {
el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
} else if ( el && el.length ) {
filter(el, type, fn);
}
};
})();
// usage
addEvent( document.getElementsByTagName('a'), 'click', fn);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment