-
-
Save eliperelman/1636094 to your computer and use it in GitHub Desktop.
Legacy 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
<!doctype html> | |
<html> | |
<head></head> | |
<body> | |
<ul> | |
<li><a href="#">1</a></li> | |
<li><a href="#">2</a></li> | |
<li><a href="#">3</a></li> | |
</ul> | |
<ul> | |
<li><a href="#">4</a></li> | |
<li><a href="#">5</a></li> | |
<li><a href="#">6</a></li> | |
</ul> | |
<script src="legacy.js"></script> | |
<script> | |
el('ul').on('click', 'a', function(e) { | |
console.log(this); | |
console.log(e); | |
}); | |
</script> | |
</body> | |
</html> |
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
// THE GOAL | |
// Write $('ul').on('click', 'a', fn); in JavaScript | |
// It's not shorter, but it should support IE, plus the API isn't too shabby, and you could probably chain the 'on' calls: | |
(function(w) { | |
var type = w.addEventListener ? 'addEventListener' : 'attachEvent', | |
prefix = w.addEventListener ? '' : 'on', | |
el = function fn(tagName) { | |
if (!(this instanceof fn)) { | |
return new fn(tagName); | |
} | |
this.elements = document.getElementsByTagName(tagName); | |
}; | |
el.prototype.on = function(evt, tag, fn) { | |
for (var i = 0, il = this.elements.length, currentEl = this.elements[i]; i < il; currentEl = this.elements[++i]) { | |
currentEl[type](prefix + evt, function(ev) { | |
var e = ev || w.event, | |
target = e.target || e.srcElement; | |
target && target.nodeName.toLowerCase() === tag && fn.call(currentEl, e); | |
}, false); | |
} | |
return this; | |
}; | |
w.el = el; | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment