Following your own reasoning:
onclick = (e)=>{
if (e.target != notificationCtn)
notificationCtn.style.display = "none";
}
The above code fragment is instructing the interpreter to assign the property onclick
of the page’s global object a function as an event handler. Making it clear that the global object of a page in a browser is the object Window
.
Knowing this makes it easy to understand that all click events that occur on the page have been assigned a single event that only performs an action if the condition below is true.
e.target != notificationCtn
That is to say window.onclick()
only performs the action notificationCtn.style.display = "none";
if the target of the event onclick
not be notificationCtn
.
How now you want the clicks on the child elements of notificationCtn
also do not carry out the action of hiding notificationCtn
, use the property Node.parentElement
, that returns the element’s parent node, to detect whether or not the click event target is related notificationCtn
.
const notificationCtn = document.querySelector(".notification");
//onclick = (e)=>{ ...
window.addEventListener("click", (e) => {
if (e.target != notificationCtn &&
e.target.parentElement != notificationCtn) {
notificationCtn.style.display = "none";
}
});
.notification {
padding: 30px;
background: blue
}
.notification div {
padding: 10px;
background: red
}
<div class="notification">
<div>Zra</div>
<div>Zra</div>
<div>Zra</div>
<div>Zra</div>
<div>Zra</div>
</div>
This approach is not the simplest and the complexity increases as we add elements to the page.
Another way to get the same is by adding the click event to the most comprehensive container, in your case notificationCtn
, and prevent this event from bubbling up using the method Event.stopPropagation()
.
const notificationCtn = document.querySelector(".notification");
window.addEventListener("click", (e) => {
notificationCtn.style.display = "none";
});
notificationCtn.addEventListener("click", (e) => {
e.stopPropagation();
});
.notification {
padding: 30px;
background: blue
}
.notification div {
padding: 10px;
background: red
}
<div class="notification">
<div>Zra</div>
<div>Zra</div>
<div>Zra</div>
<div>Zra</div>
<div>Zra</div>
</div>