My sidebar navigation menu has multiple levels, and I want to ensure that only one button is active at a time to avoid overlapping menus

overlay menus

Is there a way to make the submenu disappear when clicked outside of it?

I want only one menu to be open at a time.

Keeping only one menu open

This is my JavaScript code:

    function toggleMenu() {
    document.getElementById("myDropdown").classList.toggle("show");
    }

    window.onclick = function(e) {
    if (!e.target.matches('dropdown-btn')) {
    var dropdowns = document.getElementsByClassName("dropdown-btn");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
    var openDropdown = dropdowns[i];
    if (openDropdown.classList.contains('show')) {
       openDropdown.classList.remove('show');
      }
    }
  }
  }

This is my HTML code:

   <div class="dropdown-menu">
    <button class="dropdown-btn">Dropdown <i class="fa fa-caret-right"></i></button>
    <div class="dropdown-container">
    <button class="dropdown-btn">Dropdown<i class="fa fa-caret-right"></i></button>
        <div class="dropdown-container">
          <a href="#">Link 1</a>
          <a href="#">Link 2</a>
          <a href="#">Link 3</a>
          </div>
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
    </div>
    </div>

I apologize for not being able to include the full code. These are the sections where I need to implement the function on.

Answer №1

It is entirely possible to achieve this effect using only html and css, without the need for JavaScript!

I've put together a simple example with basic styles to demonstrate how it can be done.

The key is to initially hide the 2nd level lists (using

.list--level-2 { display: none; }
). Then, upon hovering over a 1st level list item, reveal the corresponding 2nd level list within it (
.list__item:hover>.list { display: block; }
).

You can extend this functionality to as many levels as needed, such as for 3rd, 4th, and so on...

.list {
  list-style: none;
  background-color: rgb(75 75 75 / 100%);
  width: 200px;
  margin: 0;
  padding: 0;
}

.list--level-2 {
  display: none;
  position: absolute;
  top: 0;
  left: calc(100% + 1px);
}

.list__item {
  color: white;
  padding: .25rem;
  border-bottom: 1px solid white;
  position: relative;
}

.list__item:hover>.list {
  display: block;
}
<ul class="list list--level-1">
  <li class="list__item">
    <span class="list__name">Item 1</span>
    <ul class="list list--level-2">
      <li class="list__item">Item 1 A</li>
      <li class="list__item">Item 1 B</li>
      <li class="list__item">Item 1 C</li>
      <li class="list__item">Item 1 D</li>
    </ul>
  </li>
  <li class="list__item">
    <span class="list__name">Item 2</span>
    <ul class="list list--level-2">
      <li class="list__item">Item 2 A</li>
      <li class="list__item">Item 2 B</li>
    </ul>
  </li>
  <li class="list__item">
    <span class="list__name">Item 3</span>
    <ul class="list list--level-2">
      <li class="list__item">Item 3 A</li>
      <li class="list__item">Item 3 B</li>
      <li class="list__item">Item 3 C</li>
      <li class="list__item">Item 3 D</li>
    </ul>
  </li>
</ul>

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

Adjust ChartJS yAxes "tick marks"

I'm having trouble adjusting the scales on my yAxes and all the information I find seems to be outdated. My goal is to set my yAxes range from 0 to 100 with steps of 25. Check out this link yAxes: [ { ...

Tips for enabling the background div to scroll while the modal is being displayed

When the shadow view modal pops up, I still want my background div to remain scrollable. Is there a way to achieve this? .main-wrapper { display: flex; flex-direction: column; flex-wrap: nowrap; width: 100%; height: 100%; overflow-x: hidden; ...

Can you explain the purpose of a <div> element that is empty except for the CSS property clear:both?

Can anyone shed light on the significance of this particular tag that I stumbled upon in a legitimate html document that I recently acquired? <div style="clear: both;">&nbsp;</div> I appreciate any assistance you can offer. ...

Can images be shown on a different PHP page?

My current project involves annotating images of vials with defects. I have organized these images into folders based on their batch numbers. Each folder is named according to its respective batch number. Once all the images are uploaded, I need to retriev ...

Troubleshooting: Why isn't my Bootstrap glyphicon icon displaying

Has anyone encountered issues with the glyphicon icon not showing up on buttons in Safari or Chrome when using Bootstrap? I tried fixing it but couldn't. Any help would be greatly appreciated! <link href="css/bootstrap.min.css" rel="stylesheet"&g ...

Applying CSS borders with circular corners

Can this unique border style be achieved using only CSS? https://i.sstatic.net/wMtbG.png ...

Retrieve the CSS class definition using the console in the Chrome Developer Tools

Is there a way to automatedly extract CSS class definitions from Chrome Developer Tools? I want to retrieve the styles defined in a specific class name, similar to how it is displayed in the Styles tab on the right-hand side. I know about the getComputedS ...

Incorporate Bootstrap into your Bigcommerce stencil theme for seamless design integration

As a newcomer to BigCommerce's Stencil theme, I am looking for guidance on integrating Bootstrap into the theme for local development. Is it feasible to incorporate custom CSS and JS into the Stencil theme as well? ...

Creating a virtual roulette wheel with JavaScript

I'm currently working on creating a roulette wheel using JavaScript. While researching, I came across this example: , but I wasn't satisfied with the aesthetics. Considering that my roulette will only have a few options, I was thinking of using ...

Problem with <meta> tag occurring when initial-scale is adjusted

Initially, in the index.html file: <meta name="viewport" content="width=device-width, initial-scale=1" /> I decided to modify it to: <meta name="viewport" content="width=device-width, initial-scale=2" /> ...

Tips for resolving the issue of "Text stays in original position while image changes in the background when hovering over the text."

I'm currently working on a website and I have a question regarding how to make text stay in position while hovering over it (inside a span), and at the same time, display an image in the background that allows the text to overlay it. HTML: <ht ...

customizable path settings for sprites using css

Currently, I have a situation where I am using many sprites in my CSS file, and all the image locations are hardcoded within the CSS itself. Now, I am considering moving all these images to a CDN. The problem is that it's quite cumbersome to change th ...

The layout in Next.js production builds appears to be distinct from the layout in the

Currently, I am working on a website where I have implemented a dark theme by adding a class to the body element. Everything is functioning perfectly in the development environment, but I am encountering issues in the production build. Here is the root l ...

Drawer component from Material-UI placed on top of the sidebar

Currently, I am working on a project where I am using React TypeScript along with Material-UI. The issue that I am encountering is related to the width of the Drawer component provided by Material-UI. By default, the Drawer takes up the entire screen wid ...

Modify and refresh the MySQL database upon opening a dropdown menu (NB)

Is there a way to mark notifications as read when a user opens the notification dropdown menu, similar to the functionality on Facebook? I have a database where notifications are stored, with a field called 'notification_read' that is set to eit ...

The placement and dimensions of a transparent black filter in CSS using bootstrap 4

I am currently working with the latest version of bootstrap and I am facing some challenges with the CSS due to my lack of familiarity with it (I have very little experience with bootstrap). My goal is to add a black filter to my images (specifically thos ...

Create a canvas that extends the width and height of its parent container

Looking to create a rectangular canvas that acts as a progress bar, but struggling with setting the width and height to 100%. It doesn't seem to fill the parent container properly. Check out this example below: http://jsfiddle.net/PQS3A/ Is it fea ...

During the initial cycle, the CSS keyframes animation may experience glitches, but it will run smoothly in subsequent cycles

Seeking advice on troubleshooting a CSS keyframes animation issue. I have created an animation with 5 frames where the background image fades and transitions to the next image smoothly in all cycles, except for the first cycle where it glitches before each ...

Cannot find CSS selector during web scraping operation

I recently started exploring web scraping and I'm currently working on extracting data from the following website: Specifically, I'm focused on extracting information from a particular table. However, the data in this table is not formatted in a ...

Is it possible to trigger a modal to open automatically after a 3-second delay?

code: <script> $(document).ready(function() { setInterval(function() { $('#contact').modal(); }, 3000); }); </script> html code: <a href="#contact"><h4><i class="fa f ...