Skip to content

Instantly share code, notes, and snippets.

@jlittlejohn
Created February 26, 2013 00:54
Show Gist options
  • Save jlittlejohn/5034822 to your computer and use it in GitHub Desktop.
Save jlittlejohn/5034822 to your computer and use it in GitHub Desktop.
JS: Add Event (Vanilla)
var addEvent = (function() {
return function(elem, type, fn) {
if (document.addEventListener) {
if (elem && !elem.length) {
elem.addEventListener(type, fn, false);
}
else if ( elem && elem.length) {
var len = elem.length;
for (var i = 0; i < len; i++) {
addEvent(elem[i], type, fn);
}
}
};
}
// is IE
else if (document.attachEvent) {
return function (elem, type, fn) {
if (elem && !elem.length) {
elem.attachEvent('on' + type, function(){
return fn.call(elem);
});
}
else if (elem && elem.length) {
var len = elem.length;
for (var i = 0; i < len; i++) {
addEvent(elem[i], type, fn);
}
}
};
}
})();
// Example:
// var li = document.getElementByTagName('li');
// addEvent(li, 'click', function(e) {
// this.style.border = '1px solid red';
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment