Skip to content

Instantly share code, notes, and snippets.

@englishextra
Forked from cvan/delegate.js
Created May 6, 2016 18:58
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 englishextra/df3c2bd954ea80ae5c8c6bdbadc4afdf to your computer and use it in GitHub Desktop.
Save englishextra/df3c2bd954ea80ae5c8c6bdbadc4afdf 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