Tips to minimize a responsive Bootstrap 4 menu by clicking elsewhere

When using my bootstrap nav menu on desktop, it closes when clicking outside of it. However, this feature doesn't work on mobile devices.

I attempted to modify some code from a codepen to match the classes on my website, but it didn't work.

Below is the code I tried:

const $menu = $('#id-of-menu');

$(document).mouseup(e => {
   if (!$menu.is(e.target) // if the target of the click isn't the container...
   && $menu.has(e.target).length === 0) // ... nor a descendant of the container
   {
     $menu.removeClass('show');
  }
 });

My goal was for clicking outside the menu to hide it by removing the 'show' class, but it didn't work as expected.

SOLUTION

I found a solution to my issue here, provided by Henrywright (after adjusting class and id names).

Here is the modified code I used:

jQuery('body').bind('click', function(e) {
    if(jQuery(e.target).closest('.navbar').length == 0) {
        // click happened outside of .navbar, so hide
        var opened = jQuery('#id-of-menu').hasClass('show');
        if ( opened === true ) {
            jQuery('#id-of-menu').collapse('hide');
        }
    }
});

Answer №1

To create a collapsible menu, use the following function:

function hideMenu(){
    $('#menu-id').collapse('hide');
}

Make sure to include this in your menu items:

onclick="hideMenu()"

Answer №2

On mobile devices, the 'mouseup' event may not be available so it's recommended to use the 'click' event instead.

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

Utilize jQuery to run a script once everything is prepared and loaded

My website utilizes ajax technology, and within the ajax page, there is a piece of javascript code that needs to run only after the entire ajax page has loaded. I have attempted to use the following: $( '#ajaxdiv' ).load(function() { } However ...

Interval set does not refresh an integer

I'm struggling with a function that is supposed to show the number of milliseconds elapsed since Midnight on January 1st, 1970. I've been trying to use setInterval to update the integer every second or millisecond, but it doesn't seem to be ...

How to extract a value from a BehaviorSubject within an Angular 6 guard

I have chosen this approach because I have another guard responsible for validating the user based on a token that was previously stored. This is how it was handled in previous versions of rxjs, but now with the latest version you can no longer use map on ...

Tips for creating Multi Level dropdown menus in Bootstrap v4.1

I have implemented the dropdown class and now I am trying to create a button dropdown that will display multiple child elements at one level of the dropdown. <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" ...

Modifying the data of an HTML form using Javascript, encrypting the information, and transferring it to PHP

I am new to PHP and have a simple code management question. I would like to create an input box in HTML where someone can enter their name, and with the use of Javascript, generate a link with an encoded version of the name preceded by a website string. Wh ...

Utilizing HTML and Javascript for streaming audio and recording voice

Working on a new project that involves streaming audio files (mp3) and recording voice messages. Initially considered using Flash, but the challenge is making the website iPhone-friendly as per the client's request. Is there a technology available th ...

Getting the time difference relative to the current time using date-fns from a MySQL datetime - a step

I am trying to implement a relative time feature like ... ago in my react blog posts without relying on moment.js. The date of the post is stored in mysql using the datatime data type, for example 2023-02-01 21:25:33 This is what I have attempted in the c ...

Importing JWT in ES6SyntaxCreating ES6 imports

I'm currently developing a nodeJS web application and utilizing JWT for authentication. My code is all written in ES6 modules, so I wanted to import JWT the same way. However, it seems that the package does not fully support this method yet. Since I&a ...

How can I make the input box TextField in Material UI with React expand to full width when selected?

I am currently customizing a Material UI form where the input box (Text Field) starts off at a width of 200px. My goal is to have the input box expand to 100% width only when it is selected or clicked on. ... <FormGroup sx={{ maxWidth: "200px" ...

How to display specific JSON objects that meet particular criteria in HTML cards using Ionic and Angular?

As a beginner in Ionic/Angular, I am attempting to fetch data from a JSON file and display it using cards in the HTML. The JSON contains numerous objects that are either marked as "deTurno == true" or "deTurno == false". Here is what I have so far: publi ...

Finding it difficult to align checkbox and label in an inline Bootstrap form

I'm facing a small issue with my form that I just can't seem to fix. The form consists of various "filters" that allow users to filter the table below. However, I'm struggling to align the label and checkbox vertically despite trying multipl ...

Fullcalendar Bootstrap popover mysteriously disappears

I'm having issues with my Bootstrap popovers being hidden under the rows in FullCalendar. I've tried using container: 'body' and trigger: 'focus', but they don't seem to work. The function that's causing this proble ...

Encountering difficulties when attempting to upload to Google Cloud using a signed URL

Seeking help to troubleshoot why the video upload is not working as expected. I am able to successfully connect to my bucket using a signedURL, but when trying to upload the video, it's not functioning properly. const submitVideo = async () => { ...

Animating Text Around a Circle Using HTML5 Canvas

Can someone please help me figure out what is wrong with this code? It's not rotating as it should, and the text looks messed up. I've been trying to solve this problem for hours but can't seem to get it right. function showCircularNameRot ...

Troubleshooting Issue with InfoWindow Display on Multiple Markers in Google Maps

I'm having trouble getting my markers to show different infowindows. No matter what I do, the markers always display the content of the last "contentString" in the loop. Despite reading through multiple posts on this issue, I haven't been able t ...

Redirect link depending on JSON callback information

I experimented with utilizing JavaScript to automatically redirect website visitors based on their country. The code snippet below demonstrates how the visitor's IP is checked to determine their country, such as CN for China, and then redirects them ...

Issues with AngularJS edit functionality for records not functioning as expected

I have implemented a feature on my page where users can add objects to an array. These objects are then displayed on the page along with links for editing each item in the array. Each added item is assigned a primary key, allowing users to edit it later e ...

Tips for incorporating a CSS transition when closing a details tag:

After reviewing these two questions: How To Add CSS3 Transition With HTML5 details/summary tag reveal? How to make <'details'> drop down on mouse hover Here's a new question for you! Issue I am trying to create an animation when t ...

Error encountered in jQuery call during Page_Load

Here is the code I am using to register a javascript function on Page_Load (I also tried it on Page_Init). This javascript function switches two panels from hidden to shown based on a parameter when the page loads: protected void Page_Load(object sen ...

Error: The 'then' method cannot be invoked on an undefined object in the Parse.File.save function

I am currently utilizing the Javascript API for parse.com within an Angular JS application. My goal is to successfully save or update the user's profile picture. Below is the code snippet that I have been working with: Some HTML . . . <input type ...