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?

29th May 2017, 7:24 PM
Gastón Pinto
Gastón Pinto - avatar
5 Réponses
+ 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.
29th May 2017, 11:22 PM
Benneth Yankey
Benneth Yankey - avatar
+ 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
30th May 2017, 1:26 AM
Calviղ
Calviղ - avatar
3rd Jun 2017, 11:07 PM
Cornelius Labuschagne
Cornelius Labuschagne - avatar
0
where you are calling these functions tell me plz through buttons
30th May 2017, 12:01 AM
bilal
0
use document .onclick=function(){ document.getElementById("mySidenav").style.width="0"; } I hope will work
30th May 2017, 12:04 AM
bilal