Skip to content

Instantly share code, notes, and snippets.

@dannycroft
Created May 20, 2014 16:52
Show Gist options
  • Save dannycroft/be5219c9ebdda9a49587 to your computer and use it in GitHub Desktop.
Save dannycroft/be5219c9ebdda9a49587 to your computer and use it in GitHub Desktop.
// dollar selector
function $(C, P) {
P = P || document;
return /:first$/.test(C) ? (P = P.querySelector(C.slice(0, -6))) ? [P] : [] : [].slice.call(P.querySelectorAll(C))
}
// simple utility to add an event listener
$.on = function (CSS, parentNode, type, handler, capture) {
// in case parentNode is missing
if (typeof type !== 'string') {
capture = handler;
handler = type;
type = parentNode;
parentNode = null;
}
return $(CSS, parentNode).map(function (el) {
el.addEventListener(type, handler, capture);
return el;
});
};
// example
$.on('a', 'click', function (e) {
// prevent default
e.preventDefault();
// and show the link
alert(e.currentTarget.href);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment