-
-
Save englishextra/df3c2bd954ea80ae5c8c6bdbadc4afdf to your computer and use it in GitHub Desktop.
simple querySelectorAll wrapper + event delegation
This file contains 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
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