Skip to content

Instantly share code, notes, and snippets.

@cvan
Last active August 29, 2015 13:56
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 cvan/8892101 to your computer and use it in GitHub Desktop.
Save cvan/8892101 to your computer and use it in GitHub Desktop.
$ event delegation
function $(sel) {
if (!sel) {
return $.body;
}
var r = document.querySelectorAll(sel);
return r.length == 1 ? r[0] : Array.prototype.slice.call(r);
}
$.doc = document;
$.body = document.body;
$.win = window;
$.matches = function(el, sel) {
var matchesSelector = el.webkitMatchesSelector || el.mozMatchesSelector ||
el.oMatchesSelector || el.matchesSelector;
return matchesSelector.call(el, sel);
};
$.delegate = function(type, sel, handler) {
/*
Usage:
$.delegate('submit', 'form', function() {
alert('thanks, bro!');
});
*/
document.addEventListener(type, function(e) {
var parent = e.target;
while (parent && parent !== document) {
if ($.matches(parent, sel)) {
handler(e);
}
parent = parent.parentNode;
}
}, false);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment