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

Can the JavaScript code be altered within the client's browser?

So, I'm using JQuery Validator on my webform to validate form data. However, I haven't added any validation on the server side. I'm curious if it's possible for a user to modify the code and bypass my validations in their browser. If th ...

Using a variable to contain a loop in Jquery

Seeking assistance with a jQuery function that retrieves values from a PHP form to create a variable for an ajax call. Is it possible to include a loop within a variable? Below is a snippet of my code to provide better context: ... var teacher_ids = $( & ...

Verifying if a number is present in a textbox when inserting text (without using setTimeout)

I have an input field similar to the one shown below: <input type ="number" id="numberTxt" placeholder="Number Only"/> To ensure that the value entered is a number, I am using the following function with the keypress event: <script> ...

Using jQuery version 1.2.6 to conceal the initial li element

Recently, I encountered an issue with creating an Accordion sidebar using jQuery 1.2.6. Unfortunately, I'm not able to access a newer version of jQuery due to restrictions in the CMS settings. The problem seems to be related to a bug that is causing t ...

While running tests on a React project, the `npm test` command is successful, but unfortunately,

I created a new react app using create-react-app and included some basic components and tests. The tests work fine when running 'npm test', but I encounter an 'Unexpected token' error when using Jest to run the tests with imported compo ...

Running a shared function following every Promise resolution

Currently working on a nodejs project and utilizing bluebird.js for Promises. I'm looking to have a function executed after each .then() method in the chain. Does anyone know of a way or API within bluebird.js that supports this? Appreciate any guida ...

Utilize PHP to generate a table from data

I successfully created a table using information retrieved from my database, and everything is displaying as intended. However, I am facing an issue where adding a background color applies it to every row in the table. How can I add a background color wit ...

Dynamically loading Jquery tabs in AngularJS can enhance user experience and

I need to implement a feature that loads tabs from an array using AngularJS. $scope.hods = [ { leader_id: 1000321, staff_id: 1000321, longname: "Ooi Kok Hong", username: "ANDREW", team_role: "HOD", importance: "1", active:true }, { leader_id: 100 ...

The ashx file is triggered with every server control postback in jqgrid

I have an asp .net webforms page with a jqgrid, as well as several other server controls. The jqgrid is populated using an ashx file which retrieves data from the database and binds it successfully. Challenge Whenever a postback occurs (such as from a dro ...

Designing various paragraphs with unique styles utilizing HTML and CSS

Can someone help me with using the class tag on paragraph tags? I am trying to style a specific paragraph from an external CSS file without affecting all other paragraphs. I've searched online and learned that by adding <p class="somename" >, I ...

Need help making switch buttons in react-native?

Using the library found at this link has been quite successful on my iPhone, but it does not display properly on Android. It appears as shown here. ...

Encountering an issue while trying to utilize the firestorePlugin from vuefire in Vuejs 3 createApp. The problem is that I am receiving an Uncaught TypeError: Cannot set property '$

I recently encountered an issue in my Vue.js 3 app with the following code snippet in my main.js file: import { createApp } from "vue"; import App from "./App.vue"; import { firestorePlugin } from "vuefire"; const app = creat ...

Removing using modal with AJAX in Laravel version 10

Upon clicking to retrieve data('product-id') from the delete-btn for the first time, I was able to get $product->id and successfully delete it. However, when I attempted to delete another product, it failed. It seems like it didn't retri ...

Fetch information from the input field and send it to the Redux state

Looking for a solution - I'm working on a simple todo app where I need to store user input value in the redux state. The input value is currently stored in local state until the user clicks the "add" button. The main issue : How can I pass this input ...

Can someone confirm if a user has administrator privileges?

Is it feasible to determine if members of a discord server possess administrator privileges in a looping structure? I am aiming to prohibit individuals who hold a role below my bot in the server that belongs to me and my companions. How can I achieve this? ...

Tips for aligning the button and search bar in the center:In order

Currently still learning HTML, I'm facing an issue with centering a button and a search bar that are positioned beside each other. Despite trying multiple methods, I haven't been successful in achieving the desired centered layout while keeping t ...

Copy and paste content from Outlook, Word, or any Office software directly into the embedded browser

Our application is performing well, but there is an issue with some users copying text to Word before pasting it into the app. The HTML gets parsed out somewhat correctly, but it often includes tags from outlook or word that our XHTML engine doesn't r ...

What could be causing my AngularJS JSONP request to fail when trying to query Solr?

After attempting to query my Solr server with the provided code snippet: var url ="http://localhost:8080/solr/sdc/selectwt=json&callback=JSON_CALLBACK&q=opioid" $http.jsonp(url ).success(function(res){ console.log(res) }) An error is returned ...

Alignment of inner div within the footer

I'm struggling to align my footer navigation inline with my footer title. Check out this code snippet to see what I've tried so far: https://jsfiddle.net/nkzsufov/ I experimented with using absolute and relative positioning: .footerNav { margi ...

Fetching data using an Ajax request in PHP is encountering issues, whereas the same request is successfully

I am experiencing an issue with a simple Ajax call in ASP.NET that works fine, but encounters a strange DOM Exception when I insert a breakpoint inside the onreadystatechange function. Can anyone explain why ASP.NET seems to have some additional header log ...