I have a div
over the whole page to close a dropdown menu when the big div
is clicked. The thing is that I need pointer-events: none;
because if I don't use it, the whole page gets blocked by the big div
.
JS onclick
won't work when I have pointer-events:none;
So, I don't really know how to solve this.
function test() {
if (document.getElementById('div1').style.display == 'block') {
document.getElementById('div1').style.display = 'none';
}
else{
}
}
#big_div{
width: 100%;
height: 100%;
display: block;
pointer-events:none;
}
<div id="big_div" onclick="test()"></div>
Using pointer-events: none will disable all mouse interactions with that element. If you wanted to change the cursor property, you would have to apply the changes to the parent element. You could wrap the link with an element and add the cursor property to it.
You should use addEventListener() instead."
The answer is no.
Instead of using a div covering your whole page, put a click listener on the document, check to see if the clicked element is the menu or a child of the menu, if not then hide the menu
document.addEventListener("click",function(e){
var menu = document.getElementById("myMenu");
var target = e.target;
if(target !== menu && !menu.contains(target)){
menu.style.display = "none";
}
});
Demo
document.addEventListener("click",function(e){
var menu = document.getElementById("myMenu");
var target = e.target;
var openBtn = document.querySelector("button");
if(target !== menu && !menu.contains(target) && target !== openBtn){
menu.style.display = "none";
}
});
document.querySelector("button").addEventListener("click",function(){
document.getElementById("myMenu").style.display = "block";
});
menu {
width:120px;
height:300px;
background:#88DDFF;
display:none;
}
<menu id="myMenu"><span>some item</span></menu>
<button>Open menu</button>
pointer-events: none
means no events will come through. Instead, you should close the menu by listening to click/mousedown events on the entire document (and remove your div that is set to pointer-events: none
).
document.addEventListener('mousedown', function(e) {
// You may need a better check involving e.target because
// you won't want to close the menu when clicking inside the menu
// or on the button (if the menu is not open)
if (!e.target.contains(menuNode)) {
document.getElementById('div1').style.display = 'none';
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With