Hide the Bootstrap slide menu with jQuery by clicking anywhere on the screen

Here is a Fiddle link:
https://jsfiddle.net/r94dq2e4/

I have incorporated a slide-in menu from the left in my website using Twitter Bootstrap version 3. The menu appears when the navbar toggle button is clicked.

This is the jQuery code responsible for the sliding animation:

// Nav
(function ($) {
    'use strict';

    // Toggle classes in body to sync sliding animation with other elements
    $('#bs-example-navbar-collapse-2')
        .on('show.bs.collapse', function (e) {
            $('body').addClass('menu-slider');
        })
        .on('shown.bs.collapse', function (e) {
            $('body').addClass('in');
        })
        .on('hide.bs.collapse', function (e) {
            $('body').removeClass('menu-slider');
        })
        .on('hidden.bs.collapse', function (e) {
            $('body').removeClass('in');
        });

})(jQuery);

The current functionality works well, where the menu slides in on the first click of the navbar toggle button and slides out on the second click. However, I aim to improve this behavior so that clicking anywhere on the page outside of the menu area will hide the menu.

Below is the HTML structure of the menu:

Toggle navigation Menu


                       <div class="navbar-collapse collapse" id="bs-example-navbar-collapse-2">    
                           <ul class="nav navbar-nav">
                                <li class="dropdown">   
                                    <a class="dropdown-toggle" data-toggle="dropdown" href="#">Treatments<b class="caret"></b></a>
                                    <ul class="dropdown-menu">
                                        <li><a href="#">Menu Item</span></a></li>

                                    </ul>
                                </li>
                                <li><a href="#">About Us</a></li> 
                                <li><a href="#">Meet the team</a></li> 
                                <li><a href="#">See the results</a></li> 
                                <li><a href="#">Cost</a></li> 
                                <li><a href="#">Information</a></li> 
                            </ul><!-- end navbar-nav -->
                        </div><!-- end navbar-collapse -->
                    </nav><!-- end navbar -->

I have started to implement additional jQuery code to achieve this functionality. However, I am seeking guidance on how to proceed:

/* Nav click outside hide navbar */
    $(document).click(function(e){

    // Check if click was triggered on or within #menu_content
        if ($(e.target).closest("#navbar2").length > 0) {
            return false;
        }
        // Otherwise
        // trigger your click function
         $('body').removeClass('menu-slider');
         $('body').removeClass('in');

    });

Your assistance is greatly appreciated.

Answer №1

There are three criteria to consider when deciding whether to close the menu:

  1. The element is not the navigation bar itself (.nav)
  2. The element is not the navbar container (.navbar-cllapse)
  3. The element is not a child of the navigation bar (.parents('.nav'))


if (!$(e.target).hasClass('navbar-collapse') && !$(e.target).hasClass('nav') && $(e.target).parents('.nav').length == 0) {
    $('#bs-example-navbar-collapse-2').removeClass('in');
}

You can test this in the following fiddle: https://jsfiddle.net/r94dq2e4/1/

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

Dealing with the challenge of managing multiple instances in a setup involving Ajax long polling (comet) and PHP on Lighttpd v1

I am a newcomer to this platform, so I hope to provide all the necessary details about my question. I have been attempting to set up a mechanism for "new message arrived notification" using long polling. Currently, I am triggering the polling request thro ...

Is there a way to showcase a jquery calendar with highlighted days that are unable to be clicked on (read only)?

I'm using the Jquery calendar to showcase daily room capacities, which is functioning well. However, I now want to display this calendar on my home screen in read-only mode. The days should not be highlighted, as there is no interactive feature and us ...

Troubleshooting resizing images in React using Material UI's useStyles

When attempting to resize an image using React, I am encountering a problem where adjusting the height and width of the tag with useStyles does not reduce the size of the image but instead moves it around on the page. Here is the code snippet: import { ma ...

Displaying a value in a React component using material-ui's TextField

Can anyone help me with printing the email a user enters into the textfield within the Dialog when a button is clicked? I have been struggling to achieve this due to my function's structure. Any guidance would be greatly appreciated. export default fu ...

Accessing form data within Mongoose schema hooks via JavaScript

I have a form where I've split the content into two separate MongoDB schemas. I want to access variables that are within node.js/express.js directly in mongoose schema hooks, whether through pre or post hooks of the schema. Here are my files: expres ...

What is the best way to define these variables at a global scope within my controller?

In my controller (NodeJS/Express), I have 10 routes that all use the same variables 'startDate' and 'endDate'. Is there a way to declare these globally so they don't need to be repeated in each route? Currently, my code checks if ...

Using Vue's v-bind directive with a single set of curly braces expression

Currently, I am delving into the world of Vue.js to broaden my knowledge and gain practical experience. While following a tutorial, I encountered an interesting scenario involving the addition of a class to a span element based on a condition within a v-f ...

Specify the controller to be used dynamically in an Angular directive

I want to be able to specify the controller that a directive uses by adding an attribute to the element - in other words, dynamically: HTML <div data-mydirective data-ctrl="DynamicController"></div> Angular angular.module('app', [ ...

Guide on deactivating the div in angular using ngClass based on a boolean value

displayData = [ { status: 'CLOSED', ack: false }, { status: 'ESCALATED', ack: false }, { status: 'ACK', ack: false }, { status: 'ACK', ack: true }, { status: 'NEW', ack ...

What are the top JavaScript widget libraries for a measurement reporting web application?

Embarking on a new venture to develop a web application tailored for engineers in need of reporting measurements. The key elements that form the backbone of this project include: grids charts maps After thorough research, I have delved into various java ...

What is the proper syntax for implementing the $q.all method?

During my interview, I was asked the following question. Can you identify the correct syntax for using the $q.all method? • $q.all([promise1(), promise2]).then((values) => { … }); • $q.all("promise1", "promise2").then((values) => ...

The function jquery__WEBPACK_IMPORTED_MODULE_4__.hubConnection is not recognized

I am currently trying to integrate singlar (not ASP.Core) with angular 8. If I directly include signalr and jQuery in index.html as follows: <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWS ...

Creating a dynamic HTML table using Vue 3

My table is not showing the data I'm fetching from my API. Even though I can see the data in my console.log, it's not populating the table. Could there be an issue with how I'm calling the data to display in the table? <template> < ...

Submitting a form into a database with the help of AJAX within a looping structure

Trying to input values into the database using AJAX. The rows are generated in a loop from the database, with each row containing a button column. Clicking on the button submits the values to the database successfully. The issue is that it only inserts va ...

Codeigniter displays a view with an empty variable

After submitting data from another form, I am able to successfully retrieve and print the ID with `print($id)`. However, when I try to pass it to the view, the value returned is null. Below is the code snippet: Jquery post function viewAccount(orId) { ...

Clicking on a React Material UI ListItem

I am trying to develop a clickable country list with icons next to each ListItem. However, I am facing an issue where only one item can be selected at a time in a single click. Upon clicking a new item, the previously selected one gets deselected first. He ...

Enhance User Experience - Automatically highlight the first element in Prime NG Menu when activated

I have been working on transitioning the focus from the PrimeNG menu to the first element in the list when the menu is toggled. Here is what I've come up with: In my template, I added: <p-menu appendTo="body" #menu [popup]="true&quo ...

Encountering an error with the message "SyntaxError: missing ; before statement" while attempting to utilize the Google Place Search

Lately, I've been encountering a 'SyntaxError: missing ; before statement' error while attempting to execute this ajax code in order to retrieve all nearby ATMs within a 1 km radius. var url = "https://maps.googleapis.com/maps/api/place/nea ...

Combining Two Eloquent Objects in Laravel 4.2 Based on Index

Hey everyone, I could really use your assistance with a project I'm working on using the outdated version of Laravel 4.1. Here's the situation: I have two Eloquent objects that are not related to each other. I want to combine data from these two ...

Slider Carousel for Multiple Items: Horizontal Orientation

I attempted to create a multi-item carousel slider using Bootstrap and found some code online to help me. However, the code is not functioning correctly. The issue is that the cards are not displaying next to each other horizontally as they should. Unfortu ...