When using Nav, it is necessary to only have one dropdown open at a time by closing others before opening a new

I am encountering an issue with my dropdown menu system. I have multiple submenus within a top-level dropdown menu, and the problem is that when I open one submenu and then click to open another, the first one remains open. I would like for the other submenus to automatically close when a new one is opened.

Here is a snippet of my HTML code:

<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
  <div class="container-fluid"> <a class="navbar-brand" href="#"> LOGO </a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button>
    
    <!-- Start test -->
    
    <div class="row navbar-collapse" id="navbarCollapse">
      <div class="col-md-12 order-last menu-one"> 
        <!-- Start -->
        ... (omitted for brevity)
        <!-- End --> 
      </div>
      <div class="col-md-12 order-md-last menu-two"> 
         ... (omitted for brevity)
      </div>
    </div>
    
    <!-- End test --> 
    
  </div>
</nav>

If you want to see the full code, it is available at:

I could really use some assistance in getting this menu system to function smoothly. Thank you!

Answer №1

Organize all submenus into a list and add a click listener. Upon clicking, close all submenus in the list except for the one that was clicked:

 const subMenus = [];

document.querySelectorAll('.dropend .dropdown-toggle').forEach(function(menu, index) {
    
    subMenus.push(new bootstrap.Dropdown(menu));

    menu.addEventListener('click', function(e) {

        for (let i = 0; i < subMenus.length; i++) {
            if (i !== index) subMenus[i].hide();
        }

    });

});

Here is a functional snippet of the code:

... (snipped code for brevity)

Answer №2

Implement a for loop to cycle through the elements with the attribute className=dropdown-menu and modify their className as needed

Example:

Array.from(document.querySelectorAll(".dropdown-menu")).forEach((element)=>{
   element.className == "hide"
   ? element.className = "show"
   : element.className = "hide"
})

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

Displaying the number zero in TYPO3 Fluid without it being empty or NULL

Within my TYPO3 Fluid template, I am encountering an issue where I need to display a value only if it is not empty. Currently, my approach is as follows: <f:if condition="{myvalue}"> <div class="myclass">{myvalue}</div> </f:if> Th ...

What can be used instead of the html5 output tag?

After creating a webpage with a form that includes several "number" input fields, I utilized the html output tag to showcase the results. However, when viewed in MSIE, although the calculations were successfully done, the output tag failed to display the ...

Different methods to incorporate Glyphicons without relying on Bootstrap CSS

For a recent client project, I utilized basic HTML and CSS. However, the client expressed a desire for Glyphicons to be included in the website menus. Attempting to incorporate Glyphicons with Bootstrap CSS posed challenges as it affected other aspects of ...

Cannot overflow a long flex div within parent div in CSS-Tailwind to achieve sliding effect

In the div with a class of scroll-content, I have a long list of images that I want to hide under a scroller div. My goal is to create a slide effect using arrow buttons. However, the flex box expands beyond 100% of the container. This issue arises within ...

I am looking to load an alert message simultaneously with loading an HTML link

My request is for a pop-up sweet alert to appear when the "accept your promotion" button is clicked, along with calling a relevant link at the same time. This link will update a data column in a database based on Boolean values. <script src="https://cd ...

The bootstrap code I wrote runs smoothly on Codeply's online compiler, but unfortunately it's not functioning properly in VS code

<nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="">OurCoolBrand</a> <button class="navbar-toggler" type="button&quo ...

Python - Syntax Error - Unable to Locate Element by XPath

Attempting to gather all elements of a webpage with the assistance of Selenium web driver and utilizing XPATH. Each row that needs to be gathered commences with the same text. Therefore, the following code was implemented: container = driver.find_elements ...

Resizing an image that is being pulled from a database

I am currently working on a challenging database project that seems to have hit a minor cosmetic roadblock. The database I'm dealing with loads profiles into arrays for display using a PHP while loop, making it easy to display content and allow for a ...

Assign position values to an element inside a DIV container using JavaScript, Cascading Style Sheets, and

I am currently creating some visual representations of journal issues. I am looking to showcase blocks of text using basic DIVs or other elements inside another DIV, mirroring the organization of the issue page. In order to achieve this, I need to positi ...

Chrome not displaying fonts properly

Having a font issue in Chrome where specifying "Myriad Pro", Tahoma, Arial results in weird symbols. Works fine in FF, IE, and Safari. Using font-family: Tahoma, Arial; works for all browsers including Chrome. How can Myriad Pro be achieved for IE, FF, a ...

Modify the :after property of an element using jQuery

Is there a different approach I can take to achieve this desired outcome? Currently, the code snippet below is not yielding the expected results. $('.child_flyout:after').css({'top':'20px'}); Are there any alternative method ...

Picking the Following ID Using JQuery Selector

HTML: <div id="videos"> <a href="javascript:loadAndPlayVideo('QXoIMTjk9Xg')"><img src="http://i.ytimg.com/vi/QXoIMTjk9Xg/default.jpg" id="thumb_QXoIMTjk9Xg"></a> <a href="javascript:loadAndPlayVideo('nWubf ...

Assign individual buttons to specific CSS files to update the background image on my webpage

I'm experimenting with changing the background of my webpage using Angular framework. I want to switch between different CSS files by clicking on buttons within the same page. CSS1.css body { background-image: url("./Images/mg.jpg"); } CSS2.cs ...

Tips for eliminating the jittery motion in an image gallery transition

I have a gallery of images that seems to be quite 'jumpy' when opening and closing the images, as demonstrated in this fiddle. Even after applying transform:translateZ(0); as suggested here, there doesn't seem to be much improvement in redu ...

Continuous updates triggered by mouse movement with jQuery

Can someone help me figure out why my custom description isn't following my mouse pointer during the 'mousemove' event on an image? I've provided the HTML code below: <!DOCTYPE html> <html lang="en> <head> ...

Adjust the parent's height to match the height of its content (CSS)

Could anyone assist me in figuring out how to adjust the height (red border) to fit the content (green border)? https://i.sstatic.net/l1p9q.png I'm struggling to determine which property to use, I'm aiming for this outcome but haven't had ...

How to style a MenuButton's ContextMenu individually with CSS in JavaFX

I've been trying to figure out how to adjust the coordinates of a MenuButton's Context Menu using CSS, but I haven't had any luck so far. I attempted to use the "top" property in CSS, but it didn't work. I also tried using padding, but ...

the css stylesheet fails to load properly within the Django application

While using static files in my Django app, I encountered a peculiar issue: specifying body{ } in the CSS file can alter the body's attributes, but using the div's id or class name does not affect the div's attributes. Here's an example: ...

Can you explain the concept of a host server?

Hello, I am new to using cPanel and I recently uploaded a script to my domain directory. While trying to install the script, I was prompted to input my host server information. You can view the screenshot here: https://i.sstatic.net/rrVEX.png ...

Implementing a new row insertion with jQuery/AJAX in PHP combined with a while loop

Here is a jQuery function along with a PHP file: <script> $(document).ready(function(){ $(".book_id_class").click(function(){ $("td:hidden").show(); }); }); </script> <table> <tr> <td class="text-center">Book ID</td> & ...