Skip to content

Instantly share code, notes, and snippets.

@ryantbrown
Last active April 30, 2018 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ryantbrown/2cfa00c6e73f8725b97f58db904ba9c6 to your computer and use it in GitHub Desktop.
Save ryantbrown/2cfa00c6e73f8725b97f58db904ba9c6 to your computer and use it in GitHub Desktop.
Handle a click outside of a parent element
// the parent, avoid clicks inside this element
const parent = document.getElementById('parent');
window.addEventListener('click', e => {
let elem = e.target;
// loop through the target's parent nodes to see if it matches
for ( ; elem && elem !== document; elem = elem.parentNode ) {
if(elem === parent) {
// if it matches then get out
return false;
}
}
// we know that the click came from outside the parent
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment