tips for getting the sidebar to close immediately after it has been clicked

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()">&times;</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()">&#9776;</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.

Answer №1

To determine which element was clicked during a click event on the Body, you can inspect the event.target. If the click is not on the side-bar opener, you can close the drawer.

<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>
 
 /* Define styles 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()">&times;</a>
<a href="#">cars</a>
<a href="#">planes</a>
<a href="#">boats</a>
<a href="#">cycles</a>
</div>
 
<span id="drawer-opener" style="font-size:1.5em;cursor:pointer" onclick="openNav()">&#9776;</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(e){
        if(!$(e.target).is('span#drawer-opener')) {
           $('#mySidenav').css('width', '0px');
        }
    });
}); 
</script> 
 
<script>
function openNav() {
  document.getElementById("mySidenav").style.width = "250px";
}
function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
}
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are Margins in CSS Really a Negative Aspect?

After testing my website on various browsers, I've encountered issues with margins when elements are floated. Surprisingly, Firefox displays the site correctly, but IE7 and some Linux browsers mess up the margins completely. If you're curious to ...

Styling the button in jQuery to switch between disabled and enabled

I'm currently working on creating a disabled/enable button style using jQuery. You can check out my demonstration page on Codepen for reference. In the demo, you'll notice a blue submit button. When you input text into the field, the button bec ...

Querying PHP to explore a sub-directory in search of a particular file

I've been searching for a solution to my issue. My website contains numerous files in various sub-directories within one main directory. I require a search functionality that can look for part of a file name and return the result, regardless of case s ...

The color of the left arrow on the tooltip cannot be altered

Currently, I am using a tooltip that is positioned on the right side: <i class="fas fa-question-circle text-blue" data-toggle="tooltip" data-placement="right" title="hello" ></i> I have attempted to modify the color of the too ...

Display a single qTip tooltip on click, toggling between different tooltips as needed

I am currently working on implementing qTip2 for displaying an HTML content tooltip when a link with the class "bb" is clicked. The goal is to have the tooltip open the div with the class 'tooltiptext' when a link with class 'bb' is cli ...

Using innerHTML to replaceAll also modifies characters within the tags

I created a custom function to emphasize specific strings within a text by surrounding them with span tags and updating the content using the innerHTML property of the targeted element. However, I encountered an issue while working with innerHTML instead ...

Issue with authentication in POST request

My current challenge involves attempting a POST request with basic authentication to retrieve an access token from an API. The request requires me to include the grant_type and a code in the body of the request, as well as basic auth credentials (username ...

Positioning a div at the bottom of a webpage without using absolute positioning in HTML

Check out the fiddle. I've included some CSS to position the tab on the right side. My goal was to have those tabs in the lower right corner of the container. If I use absolute positioning for the div, it messes up the tab content width. I tried ad ...

PHP Administrator Access

When a user logs in as an admin on my website, I want certain options to be available. My concern is ensuring the security of this admin account. Currently, after the login process is authenticated, I set $_SESSION['status'] = 'authorized&ap ...

SEO optimized jQuery plugin for embedding Twitter feeds

After extensive searching, I have been unable to locate a jQuery Twitter plugin that is SEO friendly. When I say SEO friendly, I am referring to one that first loads the data in HTML and then later uses AJAX. Many plugins load solely through AJAX, making ...

AngularJS script to dynamically update a table upon selecting an option from the dropdown menu

Just starting out with Angularjs and facing a challenge. I have a table with a "Update" button on the UI and a drop-down option in the 3rd column. The requirement is, upon selecting an option from the drop-down and clicking the "Update" button, the values ...

Utilizing jQueryUI for rendering tabbed content with JSON data

Although I have the ability to load JSON data that is returned (appearing "as is" in my HTML page), I am facing an issue where the raw JSON data does not disappear. The code I have used is as follows: $( "#tavole" ).tabs({ cache : false, event: "m ...

What is the best way to incorporate styled components and interpolations using emotion theming?

I've been building a React web application with a dynamic theme feature using the emotion-theming library. This allows users to switch between different environments, each with its own unique theme. To achieve this, I created my own CustomThemeProvide ...

Applying CSS to Dynamic JavaScript Elements: A Guide to Styling Without In-line Code

I'm a beginner in web development and I've been experimenting with applying styles to dynamically generated div elements using JavaScript. So far, I've only been able to manually add inline styling through this function: function applyStyle( ...

Animate using jQuery with a swinging motion from front to back

Can anyone spot the issue in this code? const moveRopes = function() { $("#ropes").animate({"left": "-40px"}, 1000, function() { $(this).animate({"left": "40px"}, 1000) }); setTimeout(moveRopes, 2000); } ...

Navigating pages within Bootstrap tabs

Struggling to implement pagination within Bootstrap tabs nested inside a modal. The code snippet in question is as follows: <div id="myModal1" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div ...

A Python CGI script that is able to accept and process data submitted

I have been working on a python program to gather data from an HTML form. Here is the snippet of my HTML code: <html> <head> <title> NBA Survey! </title></head> <form method = "POST" action = "result.py"> <hr> Who ...

Applying a CSS class to a newly generated row with JavaScript

I have a JSP page where I dynamically add rows to a table using a different Javascript function than in my previous query. While I can add elements to the table columns, I'm unable to apply a style class that is defined in a CSS file. Here is my Java ...

Creating HTML code that is optimized for mobile devices

My front end design is based on the CSS stylesheet from W3Schools.com, which includes a class property called "w3-rightbar" for adding a thick right border. However, I encountered an issue where I needed to hide this "w3-rightbar" specifically on mobile vi ...

Confirming deletion in Rails using Jquery AJAX

I've managed to get most of this working. Here's my Rails link: <%= link_to(image_tag('/images/bin.png', :alt => 'Remove'), @business, :class => 'delete', :confirm => 'Are you sure?', :id => ...