Skip to content

Instantly share code, notes, and snippets.

@sidisinsane
Last active March 3, 2020 20:40
Show Gist options
  • Save sidisinsane/7049f0b1ef34f507d248561980311a53 to your computer and use it in GitHub Desktop.
Save sidisinsane/7049f0b1ef34f507d248561980311a53 to your computer and use it in GitHub Desktop.
/**
* Detect a click outside of an element and run a callback function.
*
* @function clickedOutside
* @param {!Element} element - The element for which to detect an outside click.
* @param {!Function} callback - The callback function to run when a click outside is detected.
*
* @example
*
* clickedOutside(document.getElementById('foo'), function(e) {
* console.log('Clicked outside!');
* });
*/
function clickedOutside(element, callback) {
document.addEventListener('click', function(event) {
var targetElement = event.target;
do {
if (targetElement == element) {
// Clicked inside! Do nothing, just return.
return;
}
// Go up the DOM.
targetElement = targetElement.parentNode;
} while (targetElement);
callback();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment