I want the sidebar to close when cicked outside the sidebar.
Right now the sidebar closes when pressed inside the sidebar.
Please checkout the code below. I have a code sample below.
var mySidenav = document.getElementById("mySidenav");
var navigationOpen = false;
function openNav() {
document.getElementById("mySidenav").style.width = "300px";
document.getElementById("navIcon").style.visibility = "hidden";
navigationOpen = true;
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("navIcon").style.visibility = "visible";
navigationOpen = false;
}
//Instead of when clicking on the nav to close
// Make it close when clicking outside of the nav
window.onclick = function(event) {
if (event.target == mySidenav) {
console.log("mouse click2")
closeNav();
}
}
.sidenav {
padding-top: 60px;
overflow-x: hidden;
overflow-y: auto;
height: 100%;
width: 0;
position: fixed;
top: 0;
left: 0;
background-color: #fff000;
transition: 0.5s;
}
<!DOCTYPE html><html lang="en"><head></head><body><div id="navIcon" onclick="openNav()"> ☰</div><div id="mySidenav" class="sidenav"></div></body></html>
Thank you for your time!