Skip to content

Instantly share code, notes, and snippets.

@cvan
Created February 4, 2014 05:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cvan/8798617 to your computer and use it in GitHub Desktop.
Save cvan/8798617 to your computer and use it in GitHub Desktop.
simple querySelectorAll wrapper + event delegation
function $(sel) {
if (!sel) {
return document.body;
}
var r = document.querySelectorAll(sel);
return r.length == 1 ? r[0] : Array.prototype.slice.call(r);
}
$.matches = function(el, sel) {
var matchesSelector = el.webkitMatchesSelector || el.mozMatchesSelector ||
el.oMatchesSelector || el.matchesSelector;
return matchesSelector.call(el, sel);
}
$.delegate = function(type, sel, handler) {
document.addEventListener(type, function(e) {
var parent = e.target;
while (parent && parent !== document) {
if ($.matches(parent, sel)) {
handler(e);
}
parent = parent.parentNode;
}
}, false);
};
/*
Usage:
$.delegate('click', 'button', function() {
console.log('click');
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment