Having difficulty with collapsing Bootstrap side navigation menu levels

I've been searching high and low for an example that matches my current issue, but so far, no luck. I'm attempting to design a collapsible side navigation with multiple levels in bootstrap using bootstrap.js.

The problem I'm facing is that I have successfully added a second level, but when I click on a list item to expand it, the entire menu collapses. Furthermore, when I reopen the menu, the second-level menu remains open as well. Here is a snippet of my code:

    <div class="sidebar-nav">
    <p class="sidenav-header">Units and Lessons:</p>
    <ul class="nav nav-list">
        <li class="nav-header" data-toggle="collapse" data-target="#content-areas"> <span class="nav-header-primary">
            Content Areas
        </span>
        <ul class="nav nav-list collapse" id="content-areas">
            <li><a href="#" title="Title">All</a></li>
            <li><a href="#" title="Title">Urban Planning</a></li>
            <li><a href="#" title="Title">Sustainability</a></li>
            <li><a href="#" title="Title">Public Administration</a></li>
            <li data-toggle="collapse" data-target="#nav-health" data-parent="#content-areas"><a href="#" title="Title">Health</a>
              <ul class="nav-secondary nav-list collapse" id="nav-health">
                  <li><a href="#" title="Title">Introduction</a></li>
                  <li><a href="#" title="Title">Lesson: What is Epilepsy?</a></li>
                  <li><a href="#" title="Title">Lesson: Pathology</a></li>
            </ul>
            </li>
        </ul>
        </li>
        <li class="nav-header" data-toggle="collapse" data-target="#languages"> <span class="nav-header-primary">
            Languages
        </span>
        <ul class="nav nav-list collapse" id="languages">
            <li><a href="#" title="Title">All</a></li>
            <li><a href="#" title="Title">Arabic</a></li>
            <li><a href="#" title="Title">Turkish</a></li>
            <li><a href="#" title="Title">Hebrew</a></li>
        </ul>
        </li>
      </ul>  
    </div>

The issue specifically arises under the "Health" list item within the "Content Areas" section.

Any assistance would be greatly appreciated. Thank you!

Answer №1

Your code has a problem where the entire menu collapses when clicking within the list. For example, clicking on "All" within "Content Areas" collapses the entire section. The same issue occurs with the second level menu for "Health."

This issue is due to the lack of an accordion-heading specified in your markup. Check out the Bootstrap Collapse Documentation for guidance. Here's an example from the documentation:

<div class="accordion-heading">
  <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseOne">
    Collapsible Group Item #1
  </a>

Once you add the heading, your second level nav should function correctly.

I've created a fiddle for you to check. I adjusted the Content Areas according to the Documentation, and the second level menu worked as expected. I left the Languages menu items unmodified so you can see how they behave (try clicking within the list when Languages is expanded).

Answer №2

Although the concept is similar to Pitamber's example, I suggest simplifying by not adding extra classes. Instead, apply the "accordion-heading" class directly to the a tag.

<ul class="nav nav-list">
  <li>
    <a>Menu Item with No Sub-Items</a>
  </li>
  <li>
    <a class="accordion-heading" data-toggle="collapse" data-target="#submenu">
      <span class="nav-header-primary">Menu Item with Sub-Items <b class="caret"></b></span>
    </a>
    <ul class="nav nav-list collapse" id="submenu">
      <li><a href="#" title="Title">Sub Item 1</a></li>
      <li><a href="#" title="Title">Sub Item 2</a></li>
      <li><a href="#" title="Title">Sub Item 3</a></li>
      <li><a href="#" title="Title">Sub Item 4</a></li>
    </ul>
  </li>
</ul>

To enhance the design, consider adding CSS and/or JavaScript to highlight the sub-menu and change the caret icon when a menu item is expanded or collapsed.

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

What are the reasons for passing a global variable to a function?

Is there a difference between the two ways of writing this code? First Method: (function(i) { // Manipulate i here }(global_variable)) Second Method: (function() { // Manipulate global_variable here }()) What's the reason for passing a gl ...

Having trouble with the PHP WHERE query - it's not functioning

Recently delving into PHP, I have a requirement to verify a user's email in the database and redirect them to the next page if it exists. However, my SQL query seems to be malfunctioning in PHP but works fine in the SQL database. The structure of my ...

Handlebars: The property "from" cannot be accessed because it is not an "own property" of its parent and permission has been denied

My backend is built on Node.js and I am using server-side rendering with handlebars. I have a `doc` array of objects in handlebars that contains keys "content" and "from". However, when I try to loop through this array using `#each`, I encounter the error ...

Creating line breaks in Bootstrap input group formatting

My issue involves rows with checkboxes and labels, some of which are longer than others. When the browser is resized or viewed on a mobile device, the columns containing longer labels collapse to a second row while shorter labels stay beside their checkbox ...

How can I create two buttons on one line in a Struts2 form?

My form has two buttons - one for registering and the other for canceling the form. I created them using the following code: <s:submit name="cancel" key="project.button.cancel" /> <s:submit name="login" key="form.register.registerBtn" /> How ...

What are the differences between using the open prop and conditionally rendering a Material-UI Modal component?

Is there a difference in using the open prop or conditionally rendering Material-UI's Modal component and its built components? The closing transition may be lost, but are there any performance advantages when dealing with multiple Modals? Example wi ...

Encountered an issue when executing python manage.py migrate and python manage.py runserver

form.py This is the form section. from django.contrib.auth.models import User from security_app.models import UserProfileInfo from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) ...

Is there a way to turn off the "swipe to navigate back" feature in Microsoft Edge using JavaScript or jQuery?

Working on a website that features horizontal object rotation. For instance, starting with the front view of an object followed by side, back, other side, and then back to the front. In this case, there are 24 images of an object, each taken at a 15 degre ...

AngularJs input field with a dynamic ng-model for real-time data binding

Currently facing an issue with my static template on the render page. <form name="AddArticle" ng-submit="addArticle()" class="form add-article"> <input type="text" value="first" init-from-form ng-model="article.text[0]" /> <input typ ...

Unable to obtain the height of a new iframe within the DOM

Upon page load, I utilize the following code to adjust the height of the iframe based on its content's height, this aspect is functioning properly. $("iframe").height($("iframe").contents().height()); I have an iframe element on my webpage which I u ...

When attempting to pass `This.id` to PHP using AJAX, it causes an undefined index error when loaded by jQuery

I've been scouring the depths of the internet and various Website Development forums in hopes of finding a solution to my dilemma. Alas, my quest has been fruitless. Behold, the mystical html code: <div id='bottom-right-display'> ...

Nuxt.js has exceeded the maximum call stack size

Recently, I started working on a nuxt.js/vue project using a pre-built starter template. However, I have been encountering numerous error messages such as "Maximum call stack size exceeded." It's quite challenging to pinpoint the exact source of these ...

Using Vue and Vuex to wait for asynchronous dispatch in the created hook

I'm struggling to implement asynchronous functionality for a function that retrieves data from Firebase: Upon component creation, I currently have the following: created(){ this.$store.dispatch("fetchSections"); } The Vuex action looks ...

Repeating background images in CSS

Hey there! I'm having a little trouble with my background image in HTML. It's showing up multiple times in a row and despite searching online, I can't seem to find the right solution. Here is the code snippet from my file: <!DOCTYPE html& ...

I am continuously encountering an error message saying [$injector:modulerr] while working with AngularJS

I've been reviewing my JavaScript code thoroughly, but I can't seem to pinpoint any major issues. The error message I'm encountering is as follows: Uncaught Error: [$injector:modulerr] Failed to instantiate module careApp due to: Error: [$i ...

The Push Over Menu is malfunctioning and not functioning properly

I am facing an issue with pushing my menu along with the content to the right. The JS code I have is not working as expected. When I click on <div class="menu-btn toggle"></div>, the menu does not trigger. Can someone help me understand why thi ...

Step-by-step guide on using variables to apply CSS

In our table consisting of 6 rows and 2 columns, the second column displays a Font Awesome circle followed by various values in the database field (such as Outstanding, Very Good, Good, Needs Improvement, and Adequate). I am looking to dynamically change ...

Tips for uploading information and posting it on a different page with mongoDB and Node.js

I am looking to implement a feature on a website where data is submitted to MongoDB from one page, and then retrieved and displayed on another page. The technologies I am working with include node.js, express, Mongoose, and MongoDB. Currently, the data is ...

loop through the links using their unique identifiers

Here is my current code in Jade/Pug: #pm_language.dropdown(aria-haspopup='true', aria-expanded='false') button#langbutton.btn.btn-primary.dropdown-toggle(type='button', data-toggle='dropdown') Lang [RU] ...

Tornadofx highlight selected row with CSS

I am attempting to modify the background color of a selected row and apply the same change to a listview. When I use cell{backgroundColor += Color.BLACK}, it successfully changes the color, but it does not retain the selection color as intended.I have al ...