I've been reading the following:
https://css-tricks.com/dangers-stopping-event-propagation/
I want to implement this in a proper and safe way.
I would like to when I click outside the div with class container
that the console.log
is to trigger. Whenever I click inside or on the div with the class container
for it to not trigger.
Now. I could fix this on my own, however it feels like there is probably a smart solution to be able to do this no matter how many elements are inside the container div, or even how nested it may become.
The code below works for when I click on the actual div with the class container
, but not when I click on one of the elements (i.e. button) inside of the container div.
js:
document.addEventListener('click', function (event.target) {
if(document.getElementsByClassName('container')[0] !== event.target){
console.log('clicking outside the div');
}
});
html:
<div class="container">
<div>
<button>
I will be clicking here!
</button>
<div>
</div>
There must be a good practice approach to this, the following top rated answer How do I detect a click outside an element? has spooked me when looking for an answer in other questions, I'd rather ask for a proper one instead.
No jQuery please!