Last active
March 3, 2020 20:40
-
-
Save sidisinsane/7049f0b1ef34f507d248561980311a53 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* 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