Click anywhere outside the sidemenu to close it

I want the menu to behave like the side menu on Medium. When the side menu is open and the user clicks outside of #sidebar-wrapper, the side menu should close. Currently, I have to click the toggle X to close the menu.

html

<a id="menu-toggle" href="#" class="toggle more navbar-brand">logo</a>
<div id="sidebar-wrapper">
      <a id="menu-close" href="#" class="toggle">X</a>
</div

some css

#sidebar-wrapper {
    margin-left: -230px;
    left: 0;
    top: -20px;
    width: 230px;
    background: #f7f7f7;
    position: fixed;
    height: 120%;
    overflow-y: auto;
    z-index: 1000;
    -webkit-transition: all 0.4s ease 0s;
    -moz-transition: all 0.4s ease 0s;
    -ms-transition: all 0.4s ease 0s;
    -o-transition: all 0.4s ease 0s;
    transition: all 0.4s ease 0s;
}

#sidebar-wrapper.active {
    left: 230px;
    width: 230px;
    border-right: 1px solid #ccc;
    -webkit-transition: all 0.4s ease 0s;
    -moz-transition: all 0.4s ease 0s;
    -ms-transition: all 0.4s ease 0s;
    -o-transition: all 0.4s ease 0s;
    transition: all 0.4s ease 0s;
}

js

<script> 
   // menu close function
   $("#menu-close").click(function(e) {
       e.preventDefault();
       $("#sidebar-wrapper").toggleClass("active");
   });
</script>

<script>  
   // menu open function
   $("#menu-toggle").click(function(e) {
       e.preventDefault();
       $("#sidebar-wrapper").toggleClass("active");
   });
</script>

Answer №1

Give this a try

$("#menu-close").on("click", function(event) {
   event.stopPropagation();
   $("#sidebar-wrapper").toggleClass("active");
});
$("#menu-toggle").on("click", function(event) {
   event.stopPropagation();
   $("#sidebar-wrapper").toggleClass("active");
});
$(document).on("click", function(){
   if($("#sidebar-wrapper").hasClass('active')){
      $("#sidebar-wrapper").removeClass("active");
   }
});

DEMO

Answer №2

By utilizing stopPropagation, you can effectively prevent event bubbling in your code.

$("#menu-close").click(function(e) {
       e.stopPropagation();
       $("#sidebar-wrapper").toggleClass("active");
 });

  $(document).click(function(e) {
           $("#sidebar-wrapper").toggleClass("active");
  });

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

What is the best way to retrieve a file's creation date using the file System module in Node.js

I'm having trouble fetching the filename and file creation date to send to a client. I tried using fs.stat which provides birthtime but does not include the filename. So, my question is: is birthtime equivalent to the file created date? How can I sen ...

What is the best way to determine font size based on the width of the

In order to ensure that certain elements on my page do not exceed specific widths, it is crucial for me to use a monospaced font. This will limit the horizontal "stride" between characters to stay within a specified threshold. However, simply setting the ...

Transferring information to a controller using ajax in ASP.NET Core

I am encountering an issue with sending data to the controller through ajax. The value goes as "null". Can someone please assist me with this? Here are my HTML codes: <div class="modal fade" id="sagTikMenuKategoriGuncelleModal" data ...

jQuery accordion section refuses to collapse

In order to achieve the desired outcome, each Section should initially appear in a collapsed state. Panel 0 and 2 start off collapsed, however, panel 1 does not but can be collapsed upon clicking. Additionally, Panel 1 incorporates an iframe that displays ...

Issues with routing on Zeit Now platform are causing a 404 NOT FOUND error when attempting to reload pages that are not the

Recently, I purchased a Next.js template from Themeforest and attempted to deploy it to Zeit Now. This particular project is set up as a monorepo using Lerna and Yarn workspace. The code for the Next.js app can be found inside the packages/landing folder. ...

ng-grid defines different cellClass based on the value of the field

I am currently using the ng-grid and I want the column to display in a different color based on different values. I have tried, but not succeeded so far... $scope.gridOptions = { ........ columnDefs: [ { field: "status", displayName: "St ...

Receive regular updates every week for an entire month using Javascript

How can I calculate the number of check-ins per week in a month using Javascript? I have been unable to find relevant code for this task. Specifically, I am interested in determining the total count of user check-ins on a weekly basis. For example, if a u ...

Fetch a document from a NodeJS Server utilizing Express

Is there a way to download a file from my server to my machine by accessing a page on a nodeJS server? I am currently using ExpressJS and I have attempted the following: app.get('/download', function(req, res){ var file = fs.readFileSync(__d ...

What is the best way to establish a two-way connection between two arrays?

Within my application, there is an ItemsService responsible for fetching Items from the server and storing them as JSON objects in its cache. These Items may be displayed in various formats such as tables, graphs, or charts. For instance, when setting up ...

make changes to the current selection in the drop-down menu

Imagine I have a select list with 3 options: <select> <option>1</option> <option>2</option> <option>3</option> </select> My goal is to create a textfield and button that will allow me to upd ...

Steps to incorporate the latest Material Design Bottom App Bar into your project

In our company, we are currently utilizing Vue and SCSS for constructing our latest Progressive Web Application. Depending on specific conditions relating to the user's profile, we need to switch out the left drawer with a Bottom App Bar. Although we ...

Swap out internal Wordpress hyperlinks for Next.js Link Component

Currently, I am working on a project where I'm using WordPress as a headless CMS with GraphQL for my Next.js app. Most aspects are running smoothly except for the internal content links within articles that are fetched through the WP API. These links ...

How to display an HTML element conditionally with v-if based on a variable's value

Looking for a way to display a <div> element, including nested <div>s, based on the value of a variable. I'm currently using v-if, but open to better suggestions. I attempted wrapping the entire <div> in a <template v-if> as s ...

What steps can be taken to resolve the link prefetch warning in a Next.js application?

I am currently working on a Next.js application using version 13.4, and I've encountered a warning in the console: After preloading the resource at <URL>, it was not used within a few seconds of the window's load event. Please ensure that i ...

The lightbox fails to display in IE when a synchronous ajax request is triggered

I have a piece of code that displays a lightbox with the message 'Please Wait', followed by a synchronous ajax request that removes the lightbox once it's completed. This setup works perfectly in most browsers, but in Internet Explorer, the ...

Modify the onerror function of the image tag within the onerror function

Here is a way to display images using the img tag: If 1.jpg exists, show 1.jpg. If not, check for 2.jpg and display it if it exists. If neither 1.jpg nor 2.jpg exist, display 3.jpg. <img src="1.jpg" onerror="this.src='2.jpg'; this.oner ...

Error: You forgot to close the parenthesis after the argument list / there are duplicate items

I have already tried to review a similar question asked before by checking out this post, but unfortunately, I still couldn't find a solution for my problem. Even after attempting to add a backslash (\) before the quotation mark ("), specificall ...

Whenever I attempt to run the NPM install command in the Terminal, it seems to generate multiple errors

I am encountering an issue on my work laptop. I have the latest versions of Angular, Nodejs, Nodesass, and VScode installed in the local environment path. Whenever I download an Angular template from Github and try to do NPM Install, it consistently thro ...

Is there a way to dynamically expand and collapse all table rows, with the latest row always remaining visible, using pure JavaScript?

I have a form input field where I enter data. The entered data is then displayed in a table as a new row, with the most recent entry at the top. What I want to achieve is to show only the newest row in the table and hide all other rows. When I hover over ...

Angular.js - index template fails to execute controller, but other templates work flawlessly

I am facing a strange issue with my Angular application that uses ngRoute. I have set up different controllers for each template in the routes.js file: routes.js: angular.module('PokeApp', ['ngRoute']) .config(function($routeProvide ...