Collapse the accordion item when a different one is selected

Check out this code snippet that's working on jsfiddle

I'm attempting to add a function to close any open accordion items when another one is clicked. I've added a class "open", but I'm having trouble removing the class when a different item is clicked.

Currently, all items can remain open at the same time, but I want to avoid this behavior as it takes up too much space on mobile devices and causes issues with scrolling background and collapsible navigation.

$( document ).ready(function() {


    // header js
        (function($) {
        $.fn.menumaker = function(options) {  
         var cssmenu = $(this), settings = $.extend({
           format: "dropdown",
         }, options);
         return this.each(function() {
           $(this).find(".hamburger-button").on('click', function(){
             $(this).toggleClass('menu-opened');
             var mainmenu = $(this).next('ul');
             if (mainmenu.hasClass('open')) { 
               mainmenu.slideToggle().removeClass('open');
             }
             else {
               mainmenu.slideToggle().addClass('open');
               if (settings.format === "dropdown") {
                 mainmenu.find('ul').show();
               }
             }
           });
           cssmenu.find('li ul').parent().addClass('has-sub');
           
           

          

          $('#cssmenu li.active').addClass('open').children('ul').show();
            $('#cssmenu li.has-sub>a').on('click', function(){
              $(this).removeAttr('href');
              var element = $(this).parent('li');
              if (element.hasClass('open')) {
                element.removeClass('open');
                element.find('li').removeClass('open');
                element.find('ul').slideUp(200);
              }
              else {
                element.addClass('open');
                element.children('ul').slideDown(200);
                element.siblings('li').children('ul').slideUp(200);
                element.siblings('li').removeClass('open');
                element.siblings('li').find('li').removeClass('open');
                element.siblings('li').find('ul').slideUp(200);
              }
            });

        

      /*
           
          multiTg = function() {
             cssmenu.find(".has-sub").prepend('<span class="submenu-button"></span>');
             cssmenu.find('.submenu-button').on('click', function() {
               $(this).toggleClass('submenu-opened');
               if ($(this).siblings('.has-sub').hasClass('open')) {
                 $(this).siblings('ul').removeClass('open').slideToggle();
               }
               else {
                 $(this).siblings('ul').addClass('open').slideToggle();
               }
             });
           };
      */     
      
     
           if (settings.format === 'multitoggle') multiTg();
           else cssmenu.addClass('dropdown');
           
           
           
        resizeFix = function() {
          var mediasize = 1000;
             if ($( window ).width() > mediasize) {
               cssmenu.find('ul').show();
             }
             if ($(window).width() <= mediasize) {
               cssmenu.find('ul').hide().removeClass('open');
             }
           };
           resizeFix();
           return $(window).on('resize', resizeFix);
         });
          };
        })($);

        (function($){
        $(document).ready(function(){
        $("#cssmenu").menumaker({
           format: "multitoggle"
        });
        });
        })($);


});

Answer №1

What do you think of the following approach:

      cssmenu.children().each(function(element){
         if(element === mainmenu){
           continue;
         }
         element.removeClass('open');
       });
       mainmenu.slideToggle().addClass('open');

       if (settings.format === "dropdown") {
         mainmenu.find('ul').show();
       }

Prior to adding the open class, make sure to remove it from all other elements.

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 is the solution for untangling this complicated Javascript variable referencing issue?

Currently facing an issue that needs to be addressed: app.controller 'MainCtrl', ($scope, TestData) -> $scope.name = 'World' TestData.get(0).then (data)-> $scope.elem = data TestData.get(1).then (data)-> $scope ...

Enter a socket.IO chat room upon accessing an Express route

Encountering difficulty when attempting to connect to a socket.IO room while accessing a specific route in my Express application. The current setup is as follows: app.js var express = require('express'); var app = express(); var http = requir ...

What is the best way to retrieve recently inserted data using Sequelize in PostgreSql?

Is there a way to retrieve updated table values after adding a user to the "WOD" table without making an additional query? Currently, when I add a third user to my WOD table, I can only return the first two users because I am unable to access the updated ...

Tips for utilizing AJAX to send data from a specific row

<table> <tr data-id="1"> <input type="text" name="name_1" value="abc"> <input type="text" name="value_1" value="1"> <a href="load_edit_row(this)">Edit</a> </tr> <tr data-id="2"> <input t ...

Generate a byte array in JavaScript

How can a byte array be created from a file in JavaScript (or Typescript) to send to a C# WebApi service and be consumable by the C# byte array method parameter? Could you provide an example of the JavaScript code? The context here is an Angular 4+ applic ...

Develop a distinctive JavaScript solution that enables an image to appear in fullscreen upon loading the page, and then smoothly fade away after precisely

I have been trying to incorporate a feature on my Shopify frontage website where our logo appears fullscreen and then fades away or disappears after a few seconds, allowing people to access the rest of the website. However, I am facing difficulty in making ...

Create names for links using jQuery based on the data received from an AJAX response

I am currently utilizing the jQuery UI tooltip script available at this link. As a result, I have tooltip links with varying "data-id" attributes like so: <a tooltip-link data-id="12555"></a> <a tooltip-link data-id="38"& ...

Dynamic horizontal div elements laid out in a repeating pattern using CSS Grid

I'm fairly new to CSS/Html/JS and I'd like to create a row of Boxes (loaded from a json file) displayed horizontally. Something similar to this: https://i.sstatic.net/ZgxMR.png Here's the code snippet I've been using: <style> ...

Express JS: The requested resource does not have the 'Access-Control-Allow-Origin' header

Currently, I am encountering an issue with my API running on a server and the front-end client attempting to retrieve data from it. Previously, I successfully resolved the cross-domain problem, but now it seems like something has changed as I am receiving ...

Guide on uploading multipart career-form data with file paths and validation in CodeIgniter with the help of AJAX

I am facing an issue while attempting to insert job form data with file uploading and validation in PHP CodeIgniter via AJAX. The code I am using is provided below, but unfortunately, it's not functioning as expected. Can anyone help me figure out how ...

Unusual patterns observed when employing the splice method in AngularJS for ordering

Take a look at this Plunker demo link I have encountered an issue after implementing the orderby feature (line 24) in my application. When I try to add an item without priority and then add another one with priority, followed by deleting the first item, t ...

JavaScript incorporates input range sliding, causing a freeze when the mouse slides rapidly

Currently working on a custom slider and encountering an issue. When quickly moving the mouse outside the slider's range horizontally, exceeding its width, the slider doesn't smoothly transition to minimum or maximum values. Instead, there seems ...

Fixed positioning upon scrolling begins prior to reaching the uppermost point (top div)

Currently, I have implemented a feature where #filter (the white select list in my sidebar) becomes fixed when it reaches the top of the page and stays there while scrolling until it reaches the footer and is released. However, I encountered an issue wit ...

Sound did not play when certain pictures made contact with other pictures

English is not my native language and I am a beginner in programming. I know my explanation may not be perfect, but I'm trying my best to communicate my ideas clearly. Please be patient with me and offer constructive feedback instead of downvoting, as ...

Retrieve all existing Session Variables that start with a specific prefix

Hey everyone, I have set up a series of session variables using an id as part of the name. For example, I have these variables: $_SESSION['test_variable_1']; $_SESSION['test_variable_2']; $_SESSION['test_variable_3']; I&apos ...

My confidential environment variables are being inadvertently revealed to the client by Next.js

I am encountering a problem with my project in which an environment variable is being revealed to the browser. Despite the documentation stating that only environment variables prefixed with NEXT_PUBLIC_ should be accessible in the browser environment, all ...

Switch a div to a computed location

I'm having trouble getting this code to animate a div to a calculated position. Can someone please help me troubleshoot? $(document).ready(function() { var is_Clicked = false; $("#togglebutton").click(function() { if (is_Cli ...

`I noticed that the CSS appears differently when viewed in Mozilla compared to Chrome``

Why do the images with the same CSS property appear different in Chrome and Mozilla? I want them all to float left with equal margins between them, covering the complete area horizontally despite having varying image widths. I'm unsure why there is a ...

What is the best way to iterate through a JSON object using the stages array provided?

I am facing an issue with parsing the provided json to display the desired output on the screen. These are the steps I need to follow for parsing this json: 1. Extract the stages array from the json - for example, stages ["check_dependency_progress", "sh ...

Retrieve request body/header variables in JWT strategy using Nest JS

Is there a way to retrieve the header variables or request body in a strategy? The JWT structure within the JwtStrategy currently appears as follows: @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor( private re ...