Prevent Bootstrap 4.5 navbar menu dropdowns from automatically closing when you open another dropdown

I have modified a Bootstrap 4.5 navbar menu to function as a sidemenu. It is working properly, but I am facing an issue with the dropdowns within the menu. When I open one dropdown, it automatically closes another that was open previously. I want to allow users to open multiple dropdowns simultaneously.

Here is my current code:

    $('a.dropdown-item').on('click', function(e){
     e.stopPropagation();
    });
    
    $('a#navbarDropdown.nav-link.dropdown-toggle').on('click', function(e){
     e.preventDefault();
    });
    
    //sidebar menu
    var fixHeight = function() {
    $('.navbar-nav').css(
      'max-height',
      document.documentElement.clientHeight - 150
    );
      };
      fixHeight();
      $(window).resize(function() {
        fixHeight();
      });
      $('.navbar .navbar-toggler').on('click', function() {
        fixHeight();
      });
      $('.navbar-toggler, .overlay').on('click', function() {
        $('.mobileMenu, .overlay').toggleClass('open');
      });
.sidebar-buttons img {
  width: 30px;
  height: 30px;
  position: absolute;
  top: 10px;
}
.sidebar-buttons #pin-button {
  right: 10px;
}
.sidebar-buttons #home-button {
  right: 50px;
}
.sidebar-buttons img:hover, .sidebar-buttons img:focus {
  background: #555;
  color: #fff;
}
input.star-button[type="checkbox"] {
    content: url('assets/brand/star_empty_white.svg');
    appearance: none;
    display: inline-block;
    width: 10px;
    height: 10px;
    margin-left: 10px;
}
input.star-button[type="checkbox"]:checked {
    content: url('assets/brand/star_filled_white.svg');
}
.navbar {
  height: 50px;
}
.navbar-brand img {
  left: 50px;
  top: 0;
  width: 130px;
}
h1#header-text {
  position: absolute;
  right: 40%;
  width: 190px;
}
.bg-darknavbar {
  background: #15161A !important;
}
.dropdown-menu {
  background-color: transparent;
}
.dropdown-item {
  color: #fff;
  padding: 0;
}
a.nav-link {
  font-family: "Cera-PRO-Bold", Arial Black, Sans-serif !important;
  font-size: 0.9375em;
}
a.dropdown-item {
  font-family: "Cera-PRO-Regular", Arial, Sans-serif !important;
  font-size: 0.75em;
}
.dropdown-item:hover, .dropdown-item:focus {
  color: #fff;
  background-color: transparent;
  text-decoration: underline;
}
.nav-link.dropdown-toggle {
  width: 240px;
  border-bottom: 1px solid rgba(255, 255, 255, 1);
}
.dropdown-toggle::after {
  float: right;
  margin-top: 16px;
}
.navbar-collapse {
  background-color: #15161A !important;
}
.mobileMenu {
  -webkit-transform: translateX(-100%);
  transform: translateX(-100%);
  position: fixed;
  top: 50px;
  bottom: 0;
  margin: auto;
  left: 0;
  -webkit-transition: all ease 0.25s;
  transition: all ease 0.25s;
  width: 300px;
  background: #2E3138 0% 0% no-repeat padding-box;
  opacity: 92%;
}
.mobileMenu.open {
  -webkit-transform: translateX(0%);
  transform: translateX(0%);
}
.mobileMenu .navbar-nav {
  overflow-y: auto;
  padding-left: 15px;
  padding-top: 50px;
}
.overlay {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  background-color: rgba(0, 0, 0, 0);
  display: none;
}
.overlay.open {
  display: block;
  z-index: 1029;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="14767b7b60676066756454203a213a27">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="66040909121512140716265248534855">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>

<nav class="navbar navbar-dark bg-darknavbar justify-content-sm-spacearound fixed-top"> 
  <button class="navbar-toggler align-self-start" type="button"> <span class="navbar-toggler-icon"></span> </button>
  <a class="navbar-brand" href="#"> LOGO </a>
    <h1 id="header-text" class="text-white cera-pro d-none d-md-block">FLEET OFFICE</h1>
  <div class="collapse navbar-collapse bg-dark p-3 p-lg-0 mt-lg-0 d-flex flex-column flex-lg-row flex-xl-row justify-content-lg-start mobileMenu"
          id="navbarSupportedContent">
    <ul class="navbar-nav align-self-stretch">
      <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li>
      <li class="nav-item dropdown"> <a
                class="nav-link dropdown-toggle"
                href="#"
                id="navbarDropdown"
                role="button"
                data-toggle="dropdown"
                aria-haspopup="true"
                aria-expanded="false"> Contracts </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown"> 
            <a class="dropdown-item" href="http://www.google.com">View Contracts <input class="star-button" type="checkbox" /></a>
            <a class="dropdown-item" href="#">Contracts Modifications <input class="star-button" type="checkbox" /></a> 
            <a class="dropdown-item" href="#">Vehicle Lease <input class="star-button" type="checkbox" /></a> 
          </div>
      </li>
      <li class="nav-item dropdown"> <a
                class="nav-link dropdown-toggle"
                href="#"
                id="navbarDropdown"
                role="button"
                data-toggle="dropdown"
                aria-haspopup="true"
                aria-expanded="false"> Quote &amp; Order </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown"> 
            <a class="dropdown-item" href="#">Quote Requests <input class="star-button" type="checkbox" /></a> 
            <a class="dropdown-item" href="#">Quotes for Review <input class="star-button" type="checkbox" /></a>
            <a class="dropdown-item" href="#">Vehicles Orders <input class="star-button" type="checkbox" /></a>
            <a class="dropdown-item" href="#">Release Quotes <input class="star-button" type="checkbox" checked/></a>
          </div>
      </li>
    </ul>
  </div>
<nav>
<div class="overlay"></div>

I've been struggling for a few days to enable users to toggle multiple drop downs open at the same time. While I did manage to get them to open simultaneously at one point, they then became unresponsive and couldn't be closed. Any help would be greatly appreciated.

Answer №1

It would have been ideal if the events Bootstrap offers for dropdown elements opening and closing could handle this situation completely.

However, I couldn't find the clickEvent property mentioned in https://getbootstrap.com/docs/4.6/components/dropdowns/#events anywhere. Additionally, the order of firing for hide.bs.dropdown and show.bs.dropdown was incorrect (first hiding the element that is closing due to another one being opened, and then showing the one that should be open.)

As a result, I had to include a direct click handler on the dropdown trigger link here. When this handler is triggered, we save that element as lastTrigger. Then, in the event when the dropdown is hidden, we check if it is equal to the relatedTarget of the event. If they match, it indicates that the dropdown was closed explicitly by clicking a link; if not, it means the closure was due to another dropdown opening - in which case, we prevent the default event.

$('.navbar .navbar-toggler').on('click', function() {
  //fixHeight();
});
$('.navbar-toggler, .overlay').on('click', function() {
  $('.mobileMenu, .overlay').toggleClass('open');
});

let lastTrigger = null;
$('.nav-link.dropdown-toggle').on('click', function() {
  lastTrigger = this;
});

$('.dropdown').on('hide.bs.dropdown', function(e) {
  if (lastTrigger && lastTrigger !== e.relatedTarget) {
    e.preventDefault();
  }
})
[CSS styles]
[Bootstrap CDN links]

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

When configuring Webpack with a rule array, JSX is not properly recognized by the tool

Here is the configuration for my webpack setup: const path = require('path'); module.exports = { entry: './src/entry.jsx', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist&ap ...

Strategies for populating an empty JavaScript array with search results obtained from a PHP form submission

Blank Array: <script type="text/javascript"> var itemList=[]; </script> PHP Form: <form id="itemForm" action="" method="POST"> <div class=".col-md-6"> <div id="scrollable-dropdown-menu"> <input class="typeahead" ...

Issues with validating the input in the form

Having trouble getting the unique user name check to work while using the jQuery valid8 plugin to validate a register form. Here is the code for Register.php <?php include ("db.php"); ?> <script src='js/jquery-1.4.2.min.js' type=' ...

Using an external HTML file to import a template into Vue.js single file components

I've been tackling a Vuejs project that involves using vue-property-decorator in single file components. I'm trying to figure out how to import the template from an external HTML (or different) file, but so far I haven't found a solution. I& ...

What is preventing the angular.bootstrap code from functioning properly in AngularJS versions prior to V1.6?

Can someone explain why when using the URL http://code.angularjs.org/snapshot/angular.js everything works fine in my code within the <script> tag, but when I switch to https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js, Angular does ...

What could be causing the inconsistency in this animation, with its choppy movements and occasional lengthy delays before actions are

The animation using jQuery seems to be running inconsistently across different browsers. In Firefox, the animation appears choppy, and in both Firefox and Chrome, there is often a noticeable delay of around 1 second before the animation begins (even though ...

How to add an external JavaScript file to a nuxt.js webpage

Need some help with a simple query. I'm looking to incorporate this widget code from CodePen into my Nuxt.js project. The code works fine when using RAW HTML: <!DOCTYPE html> <html> <head></head> <body> <dev-widge ...

Increasing the size of a container without displacing the elements beneath it

There is an element on my webpage that, when hovered over, expands to reveal hidden text. The issue I'm facing is that this expansion causes the content below it to shift position. I attempted to use position:absolute, but it did not have the desired ...

What is the process for retrieving an excel file from the backend to the frontend?

I am currently facing an issue where I want to initiate a browser download of an excel file that is generated in my backend. However, I am struggling to figure out how to pass this type of response. app.get('/all', function (req, res) { db.q ...

AngularJs Resource provides the functionality to pass optional parameters through the URL

Currently, I am utilizing this type of resource: var Products = $resource('companies/:companyId/products') However, the issue arises when I attempt to access the products from all companies via the URL companies/products. Instead of receiving the ...

Utilizing Bootstrap 4 to Wrap Text Around Images

Concerning Bootstrap 4: Examine this HTML/CSS code that is not currently responsive (missing Bootstrap "col-"). The Lorem Ipsum text wraps around the image on the right side and below it due to float-left. <img class="pr-3 pb-3 float-left" src="~/Im ...

Tips for wrapping text around image using Bootstrap 4 without using the float property

Is it possible to have text wrap around an image using Bootstrap 4 without using floats? Below is the code I currently have: <article class="row single-post mt-5 no-gutters"> <div class="image-wrapper col-md-6"> <?php the_ ...

Tips for avoiding unnecessary re-renders when using a functional component and react hooks:

Problem: When a user enters a room code in the input field, the web application re-renders, causing the socket to disconnect and reconnect. Scenario: I am developing a multiplayer game using technologies like Socket.io, React, Express, PostgreSql, and Nod ...

Angular's ng-disabled feature seems to be experiencing a delay in functionality

While editing the file, I have the ability to modify the filename and add additional files for versions. Once a file has been chosen, the filename edit field should be disabled immediately. Despite attempting the following code, the field remains enabled u ...

Finding the Origin and Automatically Forwarding

I'm having an issue with my code. It's not functioning as expected. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml ...

Issue with TypeScript in React Native: Error message stating that objects cannot be used as a React child (specifically found: [object Date])

Every time I attempt to display the contents of hours, I encounter an error that is puzzling to me because it seems to be related to a date object. How can I properly address the following issue : "Objects are not valid as a React child (found: [object D ...

Issue encountered while attempting to run executeJavascript()

Hello, I’m looking to insert the output of a Python function that I have stored in the variable data. However, when I attempt to insert the value of this variable using the command document.getElementById("h1-fs-s5").innerHTML, it doesn’t work as expec ...

"Utilizing Vuex: Fetch data from API when the first getter is accessed, and subsequently retrieve it from the local

I have a Vuex instance that is responsible for fetching data from an API. The initial access to the store should trigger a call to load the data from the API. Subsequent accesses should return the previously loaded data stored in store.empresas. This is th ...

Ways to adjust Safari printing margins using CSS to achieve borderless printing

I am struggling to eliminate margins when printing a webpage to PDF in Safari. Despite setting the page size to 'A4 borderless' in the print dialogue, Safari on OSX continues to add extra margins around my HTML. Enabling 'print backgrounds&a ...

How can we distinguish a login form to enable autocomplete functionality?

A common issue arises with login forms that allow web browsers to save usernames and passwords. Consider a scenario where a user changes their password from "Password01" to "Password02". Unfortunately, the browser does not recognize the password reset form ...