Skip to content

Instantly share code, notes, and snippets.

@mythz
Last active March 4, 2021 14:56
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mythz/db1996b4b87942fab84997dff73a702d to your computer and use it in GitHub Desktop.
Save mythz/db1996b4b87942fab84997dff73a702d to your computer and use it in GitHub Desktop.
3 missing JS functions
let $ = (sel, el) => typeof sel === "string" ? (el || document).querySelector(sel) : sel || null,
$$ = (sel, el) => Array.prototype.slice.call((el || document).querySelectorAll(sel));
function on(sel, handlers) {
$$(sel).forEach(e => {
Object.keys(handlers).forEach(function (evt) {
let fn = handlers[evt];
if (typeof evt === 'string' && typeof fn === 'function') {
e.addEventListener(evt, fn.bind(e));
}
})
});
}
/* Usage Examples: */
$("#preview").innerHTML = "...";
$$(`a[href="${hash}"]`).forEach(el => el.classList.add('active'));
on('.hero .tab', {
click: function(evt) { this.classList.toggle('active') }
})
on('form input', {
keyup: function(evt) { }
})
on('.menu select', {
change: function(evt) { }
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment