Last active
October 3, 2015 00:57
-
-
Save WebReflection/2358535 to your computer and use it in GitHub Desktop.
random stuff
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
function ifClickedElsewhere(el, callback) { | |
// add prioritized 'click' listener | |
document.addEventListener( | |
'click', | |
function onClick(e) { | |
var parentNode = e.target; | |
// until we reach the current node or no node at all | |
while (parentNode && parentNode !== el) { | |
// grab the parent | |
parentNode = parentNode.parentNode; | |
} | |
// in case we never reached the initial el | |
if (parentNode !== el) { | |
// we're outside the node so we can clean up | |
document.removeEventListener('click', onClick, true); | |
// and notify the callback | |
callback(el); | |
} | |
}, | |
true // capture phase, which is before bubbling | |
); | |
} | |
// in case you deal with a more updated DOM | |
function ifClickedElsewhere(el,fn) { | |
// add prioritized 'click' listener | |
document.addEventListener( | |
'click', | |
function onClick(e) { | |
// in case we clicked outside the el | |
if (!el.contains(e.target)) { | |
// we can clean up | |
document.removeEventListener('click', onClick, true); | |
// and notify the callback | |
callback(el); | |
} | |
}, | |
true // capture phase, which is before bubbling | |
); | |
} | |
// example | |
ifClickedElsewhere(document.querySelector('#id'), function (el) { | |
el.parentNode.removeChild(el); | |
}); | |
// in case el has a close button, add a click listener | |
document.querySelector('#id button.close').addEventListener( | |
'click', | |
function onClick(e) { | |
// once clicked, cleanup | |
e.currentTarget.removeEventListener('click', onClick); | |
// and trigger a click somewhere else | |
// to delegate to ifClickedElsewhere | |
document.body.dispatchEvent(new CustomEvent('click')); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment