Difficulty with collapsing and expanding levels in Bootstrap 4 sidebar navigation

Having some trouble with my vertical Nav created using bootstrap 4. I have 2 levels of lists, but when I click on one dropdown, the other dropdown doesn't close.

Here is a link to the issue: https://jsfiddle.net/thilanka/cr0Lfmd1

  <ul class="nav flex-column flex-nowrap">
             <li class="nav-item drop">
                    <a class="nav-link collapsed" href="#submenu1" data-toggle="collapse" > sub menu 1</a>
                    <div class="collapse" id="submenu1" aria-expanded="false">
                        <ul class="flex-column pl-2 nav">

                            <li class="nav-item">
                                <a class="nav-link collapsed py-1" href="#submenu1sub1" data-toggle="collapse" >sub 11</a>
                                <div class="collapse" id="submenu1sub1" aria-expanded="false">
                                    <ul class="flex-column nav pl-4">
                                        <li class="nav-item">
                                            <a class="nav-link p-1" href="#">
                                                <i class="fa fa-fw fa-clock-o"></i> Daily
                                            </a>
                                        </li>

                                    </ul>
                                </div>
                            </li>
                        </ul>
                    </div>
                </li>           
             <li class="nav-item drop">
                    <a class="nav-link collapsed" href="#submenu4" data-toggle="collapse" >sub menu 2</a>
                    <div class="collapse" id="submenu4" aria-expanded="false">
                        <ul class="flex-column pl-2 nav">

                            <li class="nav-item">
                                <a class="nav-link collapsed py-1" href="#submenu1sub3" data-toggle="collapse" >sub 22</a>
                                <div class="collapse" id="submenu1sub3" aria-expanded="false">
                                    <ul class="flex-column nav pl-4">
                                        <li class="nav-item">
                                            <a class="nav-link p-1" href="#">
                                                <i class="fa fa-fw fa-clock-o"></i> Daily
                                            </a>
                                        </li>
                                        <li class="nav-item">
                                            <a class="nav-link p-1" href="#">
                                                <i class="fa fa-fw fa-dashboard"></i> Dashboard
                                            </a>
                                        </li>
                                </div>
                            </li>
                        </ul>
                    </div>
                </li>
            </ul>

I'm looking to create a bootstrap 4 sidebar with 2 levels of menu.

Answer №1

Is it possible to achieve this using Bootstrap's own API? One solution could be to incorporate a little jQuery into your code:

Example:

$('#my-nav>.nav-item').click(function(e) {
  $('.nav-item').not(this).each(function(index, item){
    $(item).find('div.collapse.show').each(function(i, element) {
        $(element).removeClass('show');
    });
  });
});

Remember to assign an id of my-nav to the parent ul. The goal is to remove the show class from all div children except for the one that is clicked.

See DEMO

Answer №2

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JS Bin</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  </head>
  <body>
    <div class="accordion" id="accordionExample">
      <div class="">
        <div class="nav nav-pills" id="headingOne">
          <h2 class="mb-0">
            <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
              sub menu 1
            </button>
          </h2>
        </div>

        <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">
          <div class="card-body">
            <ul class="nav flex-column">
              <li class="nav-item">
                <a class="nav-link active" href="#">Orders</a>
              </li>
              <li class="nav-item">
                <a class="nav-link active" href="#">Customers</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div class="">
        <div class="" id="headingTwo">
          <h2 class="mb-0">
            <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
              sub menu 2
            </button>
          </h2>
        </div>
        <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionExample">
          <div class="card-body">
            <ul class="nav flex-column">
              <li class="nav-item">
                <a class="nav-link active" href="#">Orders</a>
              </li>
              <li class="nav-item">
                <a class="nav-link active" href="#">Customers</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <ul class="nav flex-column">
        <li class="nav-item">
          <a class="nav-link" href="#">Analytics</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Export</a>
        </li>
      </ul>
    </div>
    <script
            src="https://code.jquery.com/jquery-3.4.1.min.js"
            integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
            crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  </body>
</html>

I've implemented the Accordion feature from Bootstrap with additional navigation and some class modifications. I trust this demonstration will be beneficial.

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

A simple guide to fetching JSON data and storing it in a variable, then parsing it and displaying it

I am looking to retrieve JSON data from the Yahoo Finance API, store it in a JavaScript variable, extract specific information such as "name" and "price", and then display it in an HTML table. The JSON data can be accessed via the following link: Current ...

Leveraging functions with Ng-Repeat

I am currently dealing with two different arrays of objects. The first array contains a list of permissions groups, while the second array consists of user groups. My main goal is to compare the Group Owner (which is represented by ID 70) with the list of ...

Performing a validation check on a value upon pressing a button prior to its submission

Hey there! I'm pretty new to React and could use some help with validating a value before using it in my partialRefund function. I want to make sure the value is not empty and is numeric before proceeding with the partialRefund operation. The first ...

Dynamically and asynchronously loading numerous LinkedIn share buttons on a page

On my page, I have a grid of post thumbnails that are fetched via AJAX and can be filtered. When a user clicks on a thumbnail, a carousel opens with the selected post centered. In this carousel, each post has a LinkedIn share button integrated. The issue ...

Achieving and maintaining the center alignment of a horizontal dropdown menu

Struggling with creating a fixed, 100% width nav bar that stays centered when the page is resized? The drop down menu headings are causing issues as they seem to float left instead of staying centered. Not sure how to fix it? Take a look at the live resul ...

Tips for sending information to an Express API through AJAX

While working on a website using Express and EJS, I encountered an issue with calling an API via AJAX. The problem arises when passing two values to the AJAX data upon button click, resulting in errors. Despite trying various solutions, I'm still stru ...

The state in a functional component in React fails to update after the initial axios call

Issue : The value of "detectLanguageKey" only updates after selecting the language from the dropdown twice. Even after selecting an option from the dropdown for the first time, the detectLanguageKey remains empty and is only updated on the second selectio ...

Creating a route-guard in a Vue.js/Firebase authentication system for secure navigation

I have created a Vue.js/Firebase authentication interface following a tutorial. The app is mostly functioning properly, but I am experiencing issues with the route guard. Upon signing in and redirecting from "http://localhost:8080/home" to "http://localh ...

Exploring the distinctions among different material design frameworks

Confirming my grasp of the situation here. Material design is an interface building approach developed by Google. Material lite is Google's public implementation of this concept. serves as an independent open-source adaptation. In addition, Angul ...

Exploring the elimination of box shadow on elements that overlap

view image hereI'm experiencing an issue with my HTML code where a box shadow appears in the mobile view. Despite my efforts, I cannot seem to remove it. This problem only arises in the mobile view, leading me to believe that it may be related to how ...

Different methods of transferring PHP post information to JavaScript

Is there a cleaner and more elegant way to pass posted PHP variables to JavaScript for manipulation, rather than using inline JavaScript? I currently have a simple PHP form that posts data to specific variables and then uses inline JavaScript to handle the ...

Rails ajax is not providing the expected JSON format in the response

I've been experimenting with ajax to retrieve data from my controller. However, the json response I'm receiving is not what I expected. There might be a routing conflict causing this issue, but I'm uncertain. This is my controller setup: ...

Change the blue line to a crisp, clean white

Is it possible to customize the color of the blue line that appears when clicked? class Greetings extends React.Component { render() { return <div>Greetings {this.props.name}</div>; } } ReactDOM.render( <div> <p tabInde ...

NodeJS - Issue: The procedure specified could not be located in the bcrypt_lib.node

After upgrading from Node.js 0.12.7 to 4.2.1, I encountered an error when attempting to start my server: $ node server.js C:\Users\me\documents\github\angular-express-auth\node_modules\bcrypt\node_modules\bindi ...

Tips for submitting a form using javascript while preventing the default action

Looking for a way to submit a form in Javascript and prevent the default action? Let's explore how you can achieve this. Initially, my HTML form with the ID "contact_form" had an input element like so: <input id="contact_send_msg" type="submit" val ...

Utilizing AJAX in Tables: Implementing an Onclick Function in a Button within a Table to Access JSON Data

I am trying to trigger a function by clicking on a button and passing the position's ID as a parameter, but I am facing some difficulties in understanding how to achieve this with the given syntax. Can anyone guide me through this process? functi ...

Setting a TypeScript collection field within an object prior to sending an HTTP POST request

Encountered an issue while attempting to POST an Object (User). The error message appeared when structuring it as follows: Below is the model class used: export class User { userRoles: Set<UserRole>; id: number; } In my TypeScript file, I included ...

Form an array from a Jquery Mobile List

In my jQuery Mobile project, I have a list with unique id numbers and search query numbers. Here's an example: "<li><a href='./page.html?id=2' data-transition='slide' id=1>Name</a></li>"; and "<li> ...

Foundation 5 - ensure background-image covers the entire column width

I'm trying to achieve a unique layout using Zurb Foundation. My goal is to have two columns, each taking up half of the screen: <div class="small-6 columns"><!-- INSERT IMAGE HERE --></div> <div class="small-6 columns"> < ...

Utilizing PHP for loading a fresh webpage within a specific div element of an existing page through AJAX

<!doctype html> <head> <title>Homepage</title> <style> #header{background-color:#09C; width:100%; height:100px;} #logoandsearch{background-color:#603; width:400px; height:40px; float:left; margin-top:30px; margin-left:1 ...