0

I have made a "side-navigation" and I set it to hide and show(slide from right) by clicking the specific icon. I have made it with onclick function. Now I need to close this menu by clicking anywhere outside of the div that I want to close.

My code is

function show(){
    document.getElementById('menu-layout').classList.add('active')
    document.body.style.backgroundColor = "#7F7F7F";
};
function hide(){
    document.getElementById('menu-layout').classList.remove('active')
    document.body.style.backgroundColor = "white";
}

enter image description here

Shuvo
  • 25
  • 6
  • The way I've done this sort of thing is by adding the hide() function to document.body() and having a listener on side-panel which calls e.stopPropagation – ControlAltDel Jan 27 '21 at 20:24
  • make an overlay which is over body instead of changing color of body, then use z-index to place that overlay under the nav, then you can simply put a click event on the overlay.. putting it on body will be inefficient as it's fired on everything. there are literally thousands of examples on the interwebs – Lawrence Cherone Jan 27 '21 at 20:27
  • https://stackoverflow.com/questions/36695438/detect-click-outside-div-using-javascript – Martin Jan 27 '21 at 20:33

1 Answers1

0

You can put the side navigation in a container div, which acts as a overlay with zero opacity. The container div should fill the whole viewport. This way you could add the click handler to the container div.

pragmaticus
  • 132
  • 7