I'm trying to hide a div when the user clicks anywhere outside of the div with id "main".
I am using vanilla Javascript and would prefer not to use jQuery.
The code I have works well but whenever the user clicks inside sub-child div or any
text, it also hides the div, which is not the behavior that I want.
window.addEventListener('mouseup', function(event){
var box = document.getElementById('main');
if (event.target != box && event.target.parentNode != box){
box.style.display = 'none';
}
});
<div id="main" style="display: block; background-color: grey;">
<div id="one1">
<div id="one2" style="background-color: red;"><p>when click here should not hide<br><br>when click here should not hide<br>when click here should not hide<br>when click here should not hide</p></div>
</div>
<div id="one3"><p>when click here should not hide</p></div>
</div>
<p>when click here should hide</p>
<div id="xyz" style="background-color: green;"><p>when click here should hide</p></div>
<p>when click here should hide</p>