Last active
April 30, 2018 08:56
-
-
Save ryantbrown/2cfa00c6e73f8725b97f58db904ba9c6 to your computer and use it in GitHub Desktop.
Handle a click outside of a parent element
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
// 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