I have a button that opens a container when I click it, and closes the container for me when I hit it anywhere on the screen, except when I press inside the container.
I have two problems which I can't solve:
1- I try to make the button appear above the container with z-index, but it always appears behind the container, and so I can't give it to close again.
2- Although the button is behind the container, when I hit it, it doesn't close the container. I would like to be able to close the container by clicking on the button.
<div id="box1">
<h2>Popup</h2>
</div>
<button onclick="document.getElementById('box1').style.display='block'" id="btn-menu">button</button>
<style>
#box1{
position: absolute;
top: 10px;
left: 10px;
width: 260px;
height: 260px;
background: #E2E2E2;
padding: 20px;
z-index: 1;
}
#btn-menu{
z-index: 9;
}
</style>
<script>
window.addEventListener('mouseup', function(event){
var box = document.getElementById('box1');
if(event.target != box && event.target.parentNode != box){
box.style.display = 'none';
}
});
</script>
I would add a visible class with the display: block property and leave this property set to none by default. And then I would add an event to the button so that it toggles this class:
Now open on button, close on button press or outside the block. And it doesn't act when you click inside the block.