Skip to content

Instantly share code, notes, and snippets.

@JeffreyWay
Created March 1, 2012 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save JeffreyWay/1946898 to your computer and use it in GitHub Desktop.
Save JeffreyWay/1946898 to your computer and use it in GitHub Desktop.
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