What could be causing the side menu to not collapse?

Recently, I developed a side menu using HTML, CSS, Bootstrap, and JavaScript. The menu appears to be functioning correctly: clicking on "Student Management" reveals the corresponding submenu, while clicking on "Invoicing Management" hides the former and displays the latter. However, there is an issue where both menus appear to be closed initially. Upon rapid successive clicks on "Student Management," followed by a single click on "Invoicing Management," and then another click back on "Student Management," both menus are displayed simultaneously. Can someone shed light on why this is happening? How can this bug be rectified with illustrative code snippets provided below? The expected behavior is for only one menu to be shown at a time.

$(document).ready(function () {
    $('.collapsed').on('click dblclick', function (ev) {
        if ($('.active').length > 0 &&
            !$(this).hasClass("active")) {
            $('.active').trigger("click");
            $('.active').removeClass("active");
        }
        $(this).addClass("active");
    });
    $('.sub-menu li').on('click dblclick', function (ev) {
        ev.stopPropagation();
    })
});
.sideMenu {
    overflow: auto;
    font-family: verdana;
    font-size: 12px;
    font-weight: 200;
    background-color: #2e353d;
    width: 300px;
    height: 100vh;
    color: #e1ffff;
}

.sideMenu ul, #navbar ul,
.sideMenu li, #navbar li {
    list-style: none;

    padding: 0px;
    margin: 0px;
    cursor: pointer;
    color: #e1ffff;
}
    .sideMenu ul,
    .sideMenu li {
        line-height: 35px;
    }

.sideMenuRightArrow {
    display: inline-block;
    padding-right: 10px;
    padding-top: 10px
}

.sideMenu ul .active,
.sideMenu li .active {
    border-left: 3px solid #d19b3d;
    background-color: #4f5b69;
}

.sideMenu ul .sub-menu li.active,
.sideMenu li .sub-menu li.active {
    color: #d19b3d;
}

.sideMenu ul .sub-menu li,
sideMenu li .sub-menu li {
    background-color: #181c20;
    border: none;
    line-height: 28px;
    border-bottom: 1px solid #23282e;
    margin-left: 0px;
}

.sideMenu ul .sub-menu li:hover,
.sideMenu li .sub-menu li:hover {
    background-color: #020203;
}
/*    .sideMenu ul .sub-menu li:before,
    .sideMenu li .sub-menu li:before {
        font-family: Fontawesome;
        content: "\f105";
        display: inline-block;
        padding-left: 20px;
        padding-right: 10px;
        vertical-align: middle;
    }*/
sideMenu li {
    padding-left: 0px;
    border-left: 3px solid #2e353d;
    border-bottom: 1px solid #23282e;
}

.sideMenu li a {
    text-decoration: none;
    color: #e1ffff;
}

.sideMenu li a i {
    padding-left: 10px;
    width: 20px;
    padding-right: 20px;
}

.sideMenu li:hover {
    border-left: 3px solid #d19b3d;
    background-color: #4f5b69;
    -webkit-transition: all 1s ease;
    -moz-transition: all 1s ease;
    -o-transition: all 1s ease;
    -ms-transition: all 1s ease;
    transition: all 1s ease;
}
@media (max-width: 768px) {
    NavBar {
        visibility: visible;
    }

    .sideMenu {
        visibility: hidden;
    }
}

@media (min-width: 769px) {
    navbar {
        visibility: hidden;
    }

    .sideMenu {
        visibility: visible;
    }
}
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>SMS_Online</title>
 <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!------ Include the above in your HEAD tag ---------->

<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!------ Include the above in your HEAD tag ---------->

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
</head>

<body>
 
    <main role="main" class="container-fluid" style="padding:0px;">
        <div class="col-xs-03">
            <div class="sideMenu">
                <div class="menuItems">
                    <ul class="">
                        <li class="">
                            <a href="#">
                                <i class="fa fa-dashboard fa-lg"></i>Main Dashboard<span class="arrow"></span>
                            </a>
                        </li>
                        <li data-toggle="collapse" data-target="#studentsSubItems" class="collapsed">
                            <a href="/">
                                <i class="fas fa-user-graduate"></i>Student Management<i class="fas fa-chevron-down float-right sideMenuRightArrow"></i>
                            </a>
                            <ul class="sub-menu collapse" id="studentsSubItems">
                                <li>
                                    <a href="#">
                                        <i class="fas fa-chevron-right"></i>Student Main
                                    </a>
                                </li>
                                <li>
                                    <a href="#">
                                        <i class="fas fa-chevron-right"></i>Register Student
                                    </a>
                                </li>
                            </ul>
                        </li>
                        <li data-toggle="collapse" data-target="#invoicingSubItems" class="collapsed">
                            <a href="#">
                                <i class="fas fa-user-graduate"></i>Invoicing Management<i class="fas fa-chevron-down float-right sideMenuRightArrow"></i>
                            </a>
                            <ul class="sub-menu collapse" id="invoicingSubItems">
                                <li>
                                    <a href="#">
                                        <i class="fas fa-chevron-right"></i>Invoicing Main
                                    </a>
                                </li>
                                <li>
                                    <a href="#">
                                        <i class="fas fa-chevron-right"></i>Create an invoice
                                    </a>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </main>
</body>

</html>

Answer №1

The reason for this issue is due to incorrect javaScript logic. I have included an additional class menu alongside the collapsed class in two instances.

First instance,

<li
  data-toggle="collapse"
  data-target="#studentsSubItems"
  class="collapsed menu"
>

Second instance,

<li
  data-toggle="collapse"
  data-target="#invoicingSubItems"
  class="collapsed menu"
>

I also made modifications to your javaScript code as follows:

$(document).ready(function () {
    $(".menu").on("click", function(){
        $(this).toggleClass("collapsed");
        $(".menu").not($(this)).addClass("collapsed");
        $(".menu").not($(this)).attr("aria-expanded","false");;
        $(".menu")
          .not($(this))
          .find(".sub-menu")
          .removeClass("show");
    });
});

This implementation functions exactly as intended.

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 happens when Long AJAX requests run in SetInterval and exceed the specified interval time?

Imagine you have this line of code: setInterval(ajaxFunction,3000); The ajaxFunction in the code is a function that calls a PHP script and retrieves data. What if the request takes longer than 3 seconds? Will it stop the current request and begin again, ...

How to display the compilation date in npm

During npm run watch is running in the background, I can see a recompilation process every time I make a change to the jsx code. Is there a way for npm to display the last time a jsx file was compiled? Thank you ...

Should I avoid declaring global app variables in Angular?

After browsing several examples online, I have come across a common pattern in AngularJS code. The basic structure involves creating a new module using the angular.module() method and then retrieving it in other files within the same module. var app = ang ...

Radiant Bootstrap 3 Radio Button

Recently I've been experimenting with the new radio buttons from twitter bootstrap 3 and I'm having trouble determining which button is checked. Here is how my buttons are set up: <div class="form-group"> <label for="inputLog ...

Utilizing Ajax and JQuery to invoke a PHP function with parameters

Seeking to implement a record deletion feature using JQuery/Ajax in order to avoid the need for page reload every time a delete action is performed. I have a Movie.php file which acts as a model object for Movie and contains a function called delete_movie ...

Creating a React component to format and display a JSON array using TypeScript

This information is currently stored in a database. [ { "id": "0", "item": { "title": "City1" } }, { "id": "1", "item": { "title": "City2" } } ] The data can now be found in the city property. The data is bein ...

BorderContainer and ContentPane dojo widgets combine to create a powerful layout system

Currently, I am in a traineeship at a company where I need to use a program developed by another trainee back in 2012. I have made some updates to the program, but encountered an issue: In the original report, the web page had a layout with a column on th ...

Creating Dynamic HTML/Javascript with a Click of a Button

I am facing a challenge with implementing a callback function on a web page that triggers when a deposit is made. The issue arises from the fact that users have the freedom to add various elements such as scripts, images, iframes, etc., in the backend. My ...

Adding multiple classes with jQuery and activating them using other jQuery functions

How can I use jQuery to add an active class to menu elements that have multiple classes? The code I have tried so far is not working as expected: JQUERY $('#foo_menu li a').click(function(){ $('#foo_menu li a').removeClass(&apos ...

The issue of the Dropdown Menu Not Remaining Fixed While Scrolling

There is a challenge with a Datetime Picker Dropdown Menu not staying in place when the user scrolls. Previous attempts to use .daterangepicker {position: fixed !important;} have been unsuccessful, causing the Datetime Picker to not stay fixed in its posit ...

focusing on a single div amidst a sea of interwoven dynamically generated divs

I am currently working with the liferay framework and I am facing a challenge where I need to apply inline JavaScript to target a very specific div on my webpage. The catch is that this div is nested within multiple dynamically added divs with varying clas ...

Image from Facebook profile not displaying in <img> tag

I am currently working on a .ejs page that contains the following code snippet: <li><% if(userInfo.image=="" || userInfo.image==null || userInfo.image==undefined){ %> <img src="/assets/img/default.png" class="img-responsive pic-bordered ...

Guide to highlighting input field text using Angular

I've set up an angular page that includes an input field within its template. My goal is to highlight the text in the input field when a specific function is triggered. When I refer to "highlighting the text," I mean (check out the image below) https ...

How can Angular incorporate an external JavaScript library?

I'm currently facing an issue with importing libraries like popper, jquery, and chart.js into my Angular project. After downloading them through the CLI, I made sure to reference them in both my index.html and angular.json files. index.html <hea ...

Animating with JQuery utilizing a dynamic attribute

We are facing a challenge with animating multiple divs that share the same class name and have different attribute values: <div class="chart-bar" style="width:10%;" bar-width="100%"></div> <div class="chart-bar" style="width:10%;" bar-wid ...

I prefer to prevent the page from refreshing once the PHP code is executed

<?php $sendTo = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="45203d242835292005203d24283529206b2b29">[email protected]</a>"; //Receiver mail $name = ""; //Sender's Name $email = ""; //Sender' ...

Making an Ajax request to the GitHub API using Backbone

Currently delving into Backbone, I have encountered an issue while attempting to fetch JSON data from the GitHub API. My goal is to create a simple web application that retrieves a paginated list of open issues from the GitHub Rails repository. The stumbli ...

I'm puzzled as to why my fixed element is gravitating towards the right side of the entire screen instead of aligning with the right side of its parent element

I have inserted a code snippet that highlights my issue. I am attempting to ensure that the .navigation element remains fixed at the top of the colored divs, however, when using 'right: 0;', the .navigation element seems to shift to the right sid ...

Is there a way to merge various collections into a single collection using Node.js and MongoDB?

There are four collections in my database: 1. Division 2. Category 3. Product Group 4. Product The following are sample data entries from each collection: { "divisionid": "1", "divisioncode": "0", "divisionname": "ELECTRONICS/HOME APPLIA ...

The Nuxt image keeps disappearing every time I navigate to a new page

Whenever I have an image displayed on my Nuxt page and then navigate away from it, the image breaks and I can't figure out why. This is what my code looks like: <img :src="baseUrl + 'storage/'+ front.featured_image" alt="p ...