I encountered a problem with the Javascript toggle menu collapsing feature

I have built a custom toggle menu using Javascript:

$(document).ready(function() {
    $('.toggle').click(function () {
        if ($(this).hasClass("expanded")) {
            $(this).next().slideUp("fast");

        } else {
            $('.toggle').next().slideUp("fast").removeClass("expanded");
            $(this).next().slideDown("fast");
            $(this).removeClass("collapsed");
            $(this).addClass("expanded");
        }
    });
});

However, I am facing an issue where clicking on another menu item does not remove the "expanded" class from the other elements. I've tried various solutions but can't seem to figure it out. Any assistance on this problem would be greatly appreciated.

Answer №1

$(document).ready(function() {
    $('.toggle').click(function () {
        if ($(this).hasClass("expanded")) {
            $(this).next().slideUp("fast");
            $(this).addClass('collapsed');
            $(this).removeClass('expanded');
        } else {
            var $expandedItems = $('.expanded');
            $expandedItems.next().slideUp("fast")
            $expandedItems.addClass('collapsed');
            $expandedItems.removeClass('expanded');
            $(this).next().slideDown("fast");
            $(this).removeClass("collapsed");
            $(this).addClass("expanded");
        }
    });
});

From the feedback you provided, it sounds like you might be looking for something along these lines.

Answer №2

$(document).ready(function() {
    $('.toggle').click(function () {
        if ($(this).hasClass("expanded")) {
            $(this).next().slideUp("fast");

        } else {
            $('.expanded').removeClass('expanded');//the issue is here
            $(this).next().slideDown("fast");
            $(this).removeClass("collapsed");
            $(this).addClass("expanded");
        }
    });
});

This snippet aims to remove the expanded class from your jQuery script.

It has been tested, but feel free to reach out if you encounter any issues.

Updated version available

View Demo

Additionally, for jQuery, make sure you have all the necessary information by checking out this Demo

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

Facing compatibility problems with JavaScript and Cascading Style Sheets in Google Chrome?

Welcome to the site . Let's address a couple of issues with JavaScript and CSS: Firstly, the JS code seems to be malfunctioning only in Chrome, throwing an error that reads: 'Uncaught TypeError: Object [object Object] has no method 'on prij ...

Managing unanticipated errors in Express while utilizing async/await mechanics

Consider this TypeScript code snippet: app.get('/test_feature', function (req: Request, res: Response) { throw new Error("This is the bug"); }); app.use(logErrors); function logErrors (err: Error, req: Request, res: Response, next: NextFun ...

Ways to trigger the keyup function on a textbox for each dynamically generated form in Angular8

When dynamically generating a form, I bind the calculateBCT function to a textbox like this: <input matInput type="text" (keyup)="calculateBCT($event)" formControlName="avgBCT">, and display the result in another textbox ...

Enhancing Accessibility for the jQuery Countdown Plugin

Seeking to enhance the accessibility of my website's jQuery countdown, I am striving to adhere to WAI-ARIA guidelines. The specified requirements are as follows: Ensure the area is live so it updates dynamically with the countdown display. Avoid re ...

Sentry: Easily upload source maps from a nested directory structure

I am currently developing a NextJs/ReactJs application using Typescript and I am facing an issue with uploading sourcemaps to Sentry artefacts. Unlike traditional builds, the output folder structure of this app mirrors the NextJs pages structure, creating ...

"Obtaining a MEAN response after performing an HTTP GET

I'm currently in the process of setting up a MEAN app, however I've hit a roadblock when it comes to extracting data from a webservice into my application. While returning a basic variable poses no issue, I am unsure how to retrieve the result fr ...

Ways to access information from a SQLite database using Angular

I am a beginner in front-end/back-end communication and I need guidance on how to retrieve data from a SQLite db file to populate a page in my Angular project. I have no idea where to begin, so any resources you can recommend would be greatly appreciated. ...

Is it possible to use a full-width material-ui Button inside a Badge component?

Within a grid, I had initially used fullWidth on a Button to make it expand and fill the container. Everything was functioning correctly until I enclosed the Button in a Badge element. Now, the fullWidth property is not being applied, and the button rever ...

Ways to create two distinct "on click" actions for a single image to execute two distinct tasks

Clicking on an image will open a slider showing all images before filtering. Once filtered, only the selected images will be displayed in the slider. <div class="gallery row" id="gallery" style="margin:0;"> <!-- Grid column --> <div ...

Tips for utilizing useQuery when props change using Apollo:

I am currently facing a challenge with my BooksList component where I need to pass props down to the BooksDetails component only when a title is clicked. I am trying to figure out how to utilize an Apollo hook to query only on prop changes. I have been ex ...

Craft a hierarchical JSON structure out of a different nested JSON object [PAUSE]

Looking to transform an existing JSON object into a new object structure. Here is the current JSON object: { "name": "Parent", "children": [ { "name": "Child1", "children": [ { "name": "GrandC ...

Difficulty redirecting Ajax call to a timed-out, CAS-protected server

Our website's login system utilizes CAS for single sign-on. The CAS server is operating the JASIG CAS server at , while our web server runs on Rails at . Due to security reasons, the Rails server has a relatively short session timeout, resulting in o ...

The next button will only activate once all input forms have been completed in multiple forms

In the JavaScript code: var current_fs, next_fs, previous_fs; //fieldsets var left, opacity, scale; //fieldset properties that will be animated var animating; //flag to prevent rapid glitches from multi-clicking $(".next").click(function(){ if(animati ...

Retrieve the heading of a click-able element using jQuery

My challenge involves a list of selectable buttons with names generated dynamically from a JSON file. Each time a button is clicked, I aim to retrieve its title, which corresponds to row["name"]. Below is my relevant code snippet and the JSON data provided ...

Anchor tags created using JQuery will remain on the same page without redirecting

Presented below is the code I have utilized to construct the anchor tag along with its content. $('div#right-slide').html("<a href=\"http://www.XXXXXXXXXXXX.info/limited-specials/\" ><h1 id=\"specials\">Click Here ...

Determining whether the user has a token stored in the localStorage is a crucial step in my

I have an app that calls a Login API and returns a token. I store the token in localStorage, but I'm unsure how to validate if the user has a token to log in. What steps can I take to solve this? Below is my login page where I store the token in loca ...

What is the process for importing the required dependencies for the maps module in react-svg-map?

Exploring interactive maps led me to discover the project react-svg-map. As I followed the example provided, a certain issue caught my attention: import Taiwan from "@svg-maps/taiwan"; The developers mentioned that they have separated the map&ap ...

Offspring of div should have equal height without the top and bottom padding

Looking to ensure that the height of child divs matches the height of the parent divs. Currently, the divs expand as the page is resized. This is for search results, so there are multiple identical code blocks. function matchHeight() { $result = $(&a ...

Having trouble retrieving the default selected value using the index in Angular Material's mat-button-toggle functionality

I'm encountering an issue with setting the default value for a toggle button group. The code is simple and the toggle buttons are correctly fetching values from the index, but I can't seem to get one of them to be default selected. I tried settin ...

Encountering a peculiar error while attempting to install firebase-tools

Currently in the process of deploying my application on Firebase by following a tutorial. I encountered an issue after executing the command npm install -g firebase-tools: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" d ...