"Clicking on one item in the Bootstrap submenu doesn't close the other items,

I have this Javascript code snippet that deals with expanding and collapsing submenu items:

<script type="text/javascript>
    jQuery(function(){
        jQuery(".dropdown-menu > li > a.trigger").on("click",function(e){
            var current=jQuery(this).next();
            var grandparent=jQuery(this).parent().parent();
            if(jQuery(this).hasClass('left-caret')||jQuery(this).hasClass('right-caret'))
                jQuery(this).toggleClass('right-caret left-caret');
            grandparent.find('.left-caret').not(this).toggleClass('right-caret left-caret');
            grandparent.find(".sub-menu:visible").not(current).hide();
            current.toggle();
            e.stopPropagation();
        });
        jQuery(".dropdown-menu > li > a:not(.trigger)").on("click",function(){
            var root=jQuery(this).closest('.dropdown');
            root.find('.left-caret').toggleClass('right-caret left-caret');
            root.find('.sub-menu:visible').hide();
        });
    });
</script>

The above script works with HTML code like this:

<li class="dropdown-submenu submenu">
    <a class="trigger right-caret">Category Name</a>
    <ul class="dropdown-menu submenu">
        <li>Subcategory</a></li>
    </ul>
</li>

However, I am facing an issue where when I click on one submenu item to expand it, the previously opened ones remain open. The only way to collapse them is by clicking on each individually. Can anyone help me modify the JavaScript code to automatically collapse other submenu items when a new one is expanded?

This is just a simplified example - in reality, the subcategory list is generated dynamically using a foreach loop.

Here is a sample scenario:

Answer №1

Modified Code:

grandparent.find(".sub-menu:visible").not(current).hide();

Revised Code:

grandparent.find("li .submenu:visible").not(current).hide();

This adjustment resolved the issue for me. You can view the updated code snippet on jsFiddle with minimal styling - http://jsfiddle.net/3xz39smb/

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

jquery-multi-auto-suggest-outputs

Hey there, I've implemented a feature where the textbox is populated based on search criteria. For example, if I type 'a', items starting with 'a' will populate in the textbox. Another textbox displays party names, and it works fin ...

What is the correct procedure for utilizing variables in the parseJson function when working with string objects?

While working with the parseJson function, I have encountered a challenge where I need to incorporate a variable within three objects. Is there a way to merge a variable with the value of one object? Alternatively, can I utilize a third object to store t ...

Having trouble with incorporating a feature for uploading multiple images to the server

At the moment, I have a code snippet that allows me to upload one image at a time to the server. However, I am looking to enhance this functionality to be able to upload multiple images simultaneously. I am open to sending multiple requests to the server i ...

At times, the status code 0 and ready state 0 is returned by Ajax file uploads

After carefully reviewing the following thread: jQuery Ajax - Status Code 0? I was unable to find a definitive solution to my issue. Therefore, I am reaching out here in hopes that someone can guide me in the right direction. In my code, I have an Angul ...

Adjust scale sizes of various layers using a script

I have created a script in Photoshop to adjust the scale size of multiple layers, but I am encountering some inaccuracies. The script is designed to resize both the width and height of the selected layers to 76.39%. However, when testing the script, I foun ...

Bringing in the node-spotify or spotify-web modules to the browser for seamless integration

Has anyone successfully used Spotify's Playlist API in a browser? It seems that the web API only covers metadata, and to access the full API I need to use libspotify. Do I need to set up a Spotify API server myself or use node libraries like node-spot ...

The functionality of jQuery Isotope is not activated until the filter buttons are clicked

I am facing an issue where Isotope does not start when my webpage loads. I attempted to implement Isotope (from isotope.metafizzy.co) along with filtering buttons. Below is the HTML and JS code I am using: <div class="scroll-pane"> <div ...

Tips for implementing jQuery on HTML loaded post document.ready():

I've encountered a scenario where I have multiple HTML elements being rendered by a JavaScript function on the page: <a href="#" class="test1">Test</a> <a href="#" class="test2">Test</a> <a href="#" class="test3">Test< ...

An issue has emerged: React cannot render objects as children. The culprit appears to be an object containing keys such as {

My sanity schema, named blogs, includes a reference field called author. I am trying to use blog.author in order to fetch the author's name for my blog, but I keep encountering an error. https://i.stack.imgur.com/haotL.png The code in my Sanity blo ...

unassigned variables in a PHP email submission form

My PHP email form is not sending emails because my variables are coming up as null. I have an echo statement after my code to check if the variables have values, but they are not being printed. Only 'done' and 'email $to' are showing up ...

Error encountered while trying to update a record using NodeJS, Express, and MySQL modules due to SQL syntax

When attempting to update a MySQL record in NodeJS, I encounter an "app crashed" error in Visual Studio Code's terminal. app2.js: const express = require('express'); const mysql = require('mysql'); // establish connection cons ...

Adding JSON data to an array in Node.JS

I am facing an issue where my JSON data is successfully being appended to an array inside a JSON file. However, the problem is that it is not appending inside of the brackets in the JSON file. Below is the code snippet for my NODE if (req.method == &apo ...

Breaking or wrapping lines in Visual Studio Code

While working in Visual Studio Code, I often encounter the issue of long lines extending beyond the screen edge instead of breaking and wrapping to the next line. This lack of text wrapping can be quite bothersome. I utilize a split-screen setup on my co ...

Applying specific style properties in styled-components can vary based on certain conditions

Is it possible to apply multiple properties at once? const Button = styled.div` color: blue; opacity: 0.6; background-color: #ccc; ` I want to apply styles for the active state without having to specify conditions for each property individually. Ho ...

Display: Show view once forEach loop finishes execution

I'm facing an issue with my update query execution within a loop. Is there a way to trigger the rendering of a view once the forEach loop completes all its iterations? Here's the snippet of code: conn.query(`SELECT Id, ${sfColumn} from Lead`, ...

Tips for adjusting the size of a container to fit its child element in a flexbox layout, where the flex-direction is set to column

Below is the functional code: .container{ display: flex; background-color: lightgreen; justify-content: center; alighn-item: center; } .child{ margin-left: 10px; height: 200px; background-color: yellow; display: flex; flex-direction: ...

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 ...

Techniques, modules and functions in Javascript

How should I properly document this code snippet: // Define a collection of colors with methods colors = { // Define method for color red "red" : function() { // Do something... } // Define object for color black "black" : { // Add ...

How can selenium be best utilized in a production environment?

After creating tests for my website using selenium and javascript, I am now looking to implement them in a production environment. Currently, I have been running these tests locally with the Chrome driver. In the start section of my package.json, I execu ...

What is the best approach for inserting multiple files into MongoDB with just one JavaScript, Node JS, Shell Script, or mongofile CLI script?

Looking for a way to transfer HTML files from a directory to MongoDB using pure JavaScript, NodeJs, shell script, or mongofile CLI. Any assistance would be greatly appreciated. Thank you in advance. ...