I need a solution where clicking outside of the My DIV with the ID Container_ID
will hide all elements within the Container by setting their style to display: none;
. Currently, the JavaScript code I am using partially achieves this functionality, but it also hides the My DIV when clicking inside any part of the Container_ID
. This is not the intended behavior, especially when interacting with elements like Controls_CLASS
, ul
, li
, or Checkbox_CLASS
within the Container_ID
itself. These elements should not trigger the hiding of the entire Container_ID
when clicked, as they are part of the container.
Is there a way to improve this functionality?
JavaScript (source: https://codepen.io/marizawi/pen/YgaaMp)
window.addEventListener('mouseup', function(event) {
var cont = document.getElementById('Container_ID');
if (event.target != cont && event.target.parentNode != cont) {
cont.style.display = 'none';
}
});
div.Container_CLASS {
width: 50%;
height: 350px;
margin-top: 4px;
margin-left: 4px;
display: block;
position: absolute;
overflow-y: scroll;
}
<div class="Container_CLASS" id="Container_ID">
<div class="Controls_CLASS"><a href="#">Select All</a>|<a href="#">Reset</a></div>
<ul>
<li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="BMW" />BMW</li>
<li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="Mercedes" />Mercedes</li>
<li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="Volvo" />Volvo</li>
</ul>
</div>