Skip to content

Instantly share code, notes, and snippets.

@maddie927
Last active January 20, 2016 19:51
Show Gist options
  • Save maddie927/75d9a41e1c018c2ac371 to your computer and use it in GitHub Desktop.
Save maddie927/75d9a41e1c018c2ac371 to your computer and use it in GitHub Desktop.
// usage:
openToggler(getElement('#some-element'), getElement('#some-element-dropdown'));
// code:
function openToggler(clicker, target) {
if (!clicker || !target) return;
var setter = classSetter(target, 'open');
var opened = false;
var clickHandler = function (e) {
opened = !opened;
setter(opened);
if (opened) {
setTimeout(function () {
document.body.addEventListener('click', clickHandler, false);
});
} else {
document.body.removeEventListener('click', clickHandler, false);
}
};
clicker.addEventListener('click', clickHandler, false);
}
function classSetter(anchor, className) {
return function (on) {
var oldClassNames = anchor.className.split(/\s+/);
var idx = oldClassNames.indexOf(className);
var hasClass = !!~idx;
if (on) {
if (!hasClass) {
oldClassNames.push(className)
anchor.className = oldClassNames.join(' ');
}
} else {
if (hasClass) {
oldClassNames.splice(idx, 1);
anchor.className = oldClassNames.join(' ');
}
}
}
}
function getElement(selector) {
return document.querySelector(selector);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment