0
How to close side nav when clicking elsewhere on the screen?
I am running this script: <script> function openNav() { document.getElementById("mySidenav").style.width = "200px"; } function closeNav() { document.getElementById("mySidenav").style.width = "0"; } </script> But, the thing is that I can not manage a solution to get the side nav closed whenever the user clicks elsewhere on the screen. So, any ideas?
5 Answers
+ 4
Else where on the screen other done any node or element is the document itself. So select the document and addEventListener pointing to your closeNav() function.
+ 1
You can trigger closeNav at top level, HTML tag click event for "elsewhere" triggering
document.documentElement.addEventListener("click", function(e) {
closeNav()
e.preventDefault()
}, false)
And set stopPropagation to prevent certain elements propagate to HTML click event
document.getElementById("side-menu").addEventListener("click", e=>e.stopPropagation(), false)
Check out the sample code here..
https://code.sololearn.com/WsoA0dqf1tQS/?ref=app
+ 1
check my game https://code.sololearn.com/WF65X6DEns7o/?ref=app
0
where you are calling these functions tell me plz through buttons
0
use document .onclick=function(){
document.getElementById("mySidenav").style.width="0";
}
I hope will work