Skip to content

Instantly share code, notes, and snippets.

@eliperelman
Forked from JeffreyWay/legacy.js
Created January 18, 2012 22:04
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 eliperelman/1636094 to your computer and use it in GitHub Desktop.
Save eliperelman/1636094 to your computer and use it in GitHub Desktop.
Legacy JS
<!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>
// 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