My understanding of how the menu sidebar works is a bit unclear, but here's my issue. I want the menu sidebar to close automatically when a user clicks on a menu link item or anywhere on the body. Then, it should reopen when the menu icon is pressed. I've tried various methods, but they all seem to be either all in or all out.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<meta name="viewport" content= "width=device-width, initial-scale=1.0">
<style>
/* styling for the side menu */
.sidenav {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: white;
overflow-x: hidden;
transition: 0.5s;
border: 1px solid black;
}
.sidenav a {
padding: 3px;
margin: 5px;
text-decoration: none;
font-size: .9em;;
color: black;
display: block;
transition: 0.3s;
}
</style>
<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<a href="#">cars</a>
<a href="#">planes</a>
<a href="#">boats</a>
<a href="#">cycles</a>
</div>
<span style="font-size:1.5em;cursor:pointer" onclick="openNav()">☰</span>
<body>
<p>some random text some random textsome random textsome random text</p>
<p>some random text some random textsome random textsome random text</p>
<p>some random text some random textsome random textsome random text</p>
</body>
<script>
$(document).ready(function(){
$('body').on('click',function(){
$('#mySidenav').css('width', '0px');
});
});
</script>
<script>
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}
</script>
Whenever a user opens the menu sidebar and selects a menu item or clicks within the body area, the sidebar should automatically close. The suggestions I've seen so far are challenging for me to grasp, perhaps due to my limited understanding.