Last active
January 20, 2016 19:51
-
-
Save maddie927/75d9a41e1c018c2ac371 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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