Press anywhere else on the screen to dismiss the bootstrap menu

I've been attempting to find a solution for closing the Bootstrap menu when clicking outside of it in a mobile window size, but I just can't seem to make it work. I did manage to get it working when clicking one of the 'a' links using this code:

// This code collapses the menu buttons when clicking a link
$('document').ready(function() 
{
    if ($('a').on('click', function() 
            { 
                $('.collapse, #mainContainer').removeClass('in'); 
                $('.navbar-toggle').toggleClass('collapsed'); // button
            }));
});

But how can I close the menu by clicking outside of the menu navbar?

Here's the link to my page where you can see the issue: iwebdesign.se

I have already tried the following, but it didn't work:

Similar question

Answer №1

If you're looking to achieve different actions when clicking inside or outside of a menu (such as collapsing the menu), you can use the following code snippet to determine if the click is inside or outside the menu:

$('body').click(function(event){
  // check if the clicked element is a descendant of the menu 
  if ($(event.target).closest('.menu').length) {
    return; // do nothing if the event target is within the menu
  } else {
    // perform an action if the event target is outside the menu
     // code for collapsing menu goes here...
  }
});

You can view a working example at https://jsfiddle.net/L3qg4pa8/5/ to get a better idea of how it works.

Don't forget to update the '.menu' selector in the .closest() function with the appropriate container selector for your menu.

Answer №2

  $(document).on('click',function(){
   $('.collapse').collapse('hide');
});

You can simply paste this code snippet into your custom script or index.html file.

A big thank you to Remy for the tip! Remember, clicking outside will close/hide the Bootstrap toggle menu.

Answer №3

Below is the solution:

(window).on('click',function(){
   $('.collapse').collapse('hide');
})

Trust this helps!

Ella

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

Encountering an issue when transferring data between controllers utilizing a demo service

During my journey of learning AngularJS, I decided to create a small app that would allow data to be passed between two controllers using services. Below is the code snippet that showcases how I achieved this: The Controller Code <!DOCTYPE html> &l ...

Setting the height of columns in a Bootstrap panel to 100%

Is there a way to achieve 100% height for all three columns even without content? Check out this JSFiddle: <div class="row"> <div class="col-md-12"> <div class="shadow panel panel-default"> <div class="blue white-bord ...

Using XSLT with JavaScript

I am currently working with a set of XML files that are linked to XSLT files for rendering as HTML on a web browser. Some of these XML files contain links that would typically trigger an AJAX call to fetch HTML and insert it into a specific DIV element on ...

React Native vector icons display enigmatic symbols

I recently installed react-native-vector, but I'm seeing strange symbols when using it. Can anyone provide guidance on how to properly utilize this library? Platform: Android import React from 'react'; import {View, Text, StyleSheet} from & ...

Error with Bootstrap Layout caused by the StringBuilder

After diving into Bootstrap, I encountered an issue with the layout generated by a VB.NET page using StringBuilder. The result was a disorganized mess: Upon further inspection, it became evident that the problem extended to other sections of the page as w ...

The error message "TypeError: Cannot set property 'href' of undefined" occurred at angular.js line 12520 when trying to set $window.location.href

Has anyone tried using a directive function to redirect when clicking with ng-click? Here is the HTML code: <a ng-click="navbarlinksCtrl.clickedfr()" ng-class="{active: clickedfr()}">FR</a><br> <a ng-click="navbarlinksCtrl.clickeden( ...

Show several fresh windows

Greetings everyone. Let me explain my current situation: I have a search page where users can select a product from a drop-down list, and upon clicking a button, a gridview is displayed showing the specifications of the selected product. What I'm a ...

Managing the invocation of a promise multiple times in AngularJS, and handling some specific exceptions

After previously asking a question on handling promises multiple times in AngularJS (AngularJS handle calling promise multiple times), I am facing a new challenge. This time, I need to retrieve a list of cities, but encounter an exception. Similar to how ...

Learn the process of directing to a view in a jQuery AJAX call with Spring MVC

Below is the ajax call I am using: $.ajax({ type: "POST", url: contextPath +"/action", cache:false, dataType: 'text', data: {Id:Id}, success: funct ...

Changing an ng-repeat filter following the manual update of a text input

Utilizing jQuery auto-complete to automatically populate values as users type into a text input. <input type="text" ng-model="tags" name="tags" id="tags" value="" /> Subsequently, the ng-repeat is filtering content based on the entered text <di ...

From jQuery to ReactJS: Migrating to a Modern

As I venture into converting existing jQuery code to React.js, I must admit that I am quite new to React and still in the learning phase. So please bear with me if my questions sound a bit silly. Here is the structure I am working with: <ul> &l ...

Is the canvas refusing to disappear?

My HTML5 Canvas element is not disappearing as expected. I wrote a timer function to hide the element when the timer hits 0. I tested this using an alert flag and it worked perfectly. Problem: if (TotalSeconds <= 0) { ctx.clearRect(0, 0, canvas.w ...

Is it recommended to add the identical library to multiple iFrames?

Here's a quick question I have. So, my JSP page has 4 different iFrames and I've included JQuery UI libraries in it: <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" /> <script src="http://c ...

Utilizing jQuery to correspond with CSS media queries

Continuing from my previous question about an automatic jQuery image slider, you can refer to it here. I have made some changes in my CSS using media queries and I am trying to incorporate them into my JavaScript code using an 'if / else if' sta ...

What is the best way to select a clicked span element within a div using JQuery and then adjust the spans before and after it

<div> <span>A</span> <span>B</span> <span>C</span> <span>D</span> </div> If a user clicks on one of the spans within the div, I want to apply styles (such as text color) to that span and all prec ...

ESLint flagging "Unexpected tab character" error with "tab" indentation rule enabled

Currently, my ESLint setup includes the Airbnb plugin (eslint-config-airbnb) along with the Babel parser. I recently decided to enforce the rule of using Tab characters for indentation instead of spaces. This is how my .eslintrc file looks like: { "p ...

The console.log() displays the dictionary correctly, but trying to access it with a key results in it being undefined

I'm currently facing an issue with accessing the dictionary stored in the "workload" field of a document in Firestore. Here is the snippet of code I am struggling with: async addTask() { const projectDoc = await getDoc(doc(db, "projects", "Testing ...

Ways to Retrieve the Text From the Selected Index in Datalist Element

I need to extract the inner text of the option tag using pure JavaScript This is the HTML code I am working with: <input list="in" name="i_n" class="form-control" placeholder="Enter Item Name" required> <datalist id="in" onChange="rate(this)"&g ...

The pseudo-class for invalid input triggers CSS invalidation, even when the input field is left blank

The input property for handling invalid input is currently malfunctioning. It triggers an error even when the input field is left empty. I would like the input border to be goldenrod when it's empty, turn red if the input doesn't match the specif ...

Ways to access information received from AngularJS in a different Javascript file

I am currently using Angular to retrieve output from a controller and display it using ng-bind. However, I have another separate JavaScript file that needs to utilize a value returned from Angular. In the example code provided below, the TestAppCtrl is ca ...