"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

What is the best way to keep a <div> class anchored to the bottom of an HTML page?

I am looking to incorporate a footer into my website that stays fixed at the bottom of the screen. However, I have encountered an issue: Here is what I have attempted so far: .footer { position: absolute; width: 100%; background: #0084FF; ...

Find the ID of the clicked table row using HTML and JavaScript

Currently, I am trying to implement this code snippet: <td align="center"> <div class="dropdown"> <button onclick="DropdownShow(this)" class="btn btn-default glyphicon glyphicon-picture"></button> <div id="@TableR ...

Issue with VueJs router-link component

Whenever I click on a vuejs router-link element in my app.blade.php page navigation bar, I keep seeing an error in my console which is displayed below [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent comp ...

The specified variable will not be visible in the window object

I recently created a JavaScript code snippet that looks like this: let var1 = 1; window.var2 = 2; After running the code in the Chrome console, I entered window to inspect the global window object. Surprisingly, only the second variable appeared and the ...

Include personalized headers to the 'request'

I have configured my express server to proxy my API using the following setup: // Proxy api calls app.use('/api', function (req, res) { let url = config.API_HOST + req.url req.pipe(request(url)).pipe(res) }) In this instance, confi ...

CSS: Including an item in a list causes the <div> to expand upwards on the page instead of stretching downwards

I’m currently facing an issue with my list where, upon reaching a certain number of items (in this case 5), the list starts moving up the page instead of extending downwards as expected. I suspect that this problem is related to my use of CSS grid-templa ...

Transforming a string to a Date object using JavaScript

Can someone assist me in converting a PHP timestamp into a JavaScript Date() object? This is the PHP code I use to get the timestamp: $timestart = time(); I need help converting this timestamp into a JavaScript date object. The concept of working with d ...

avoid loading javascript in ajax layer

After struggling for days to find answers online and unsuccessfully trying different codes, I discovered a way to use ajax to dynamically change the contents of a div element and display different sliders. Here are the files if you want to take a look: Fi ...

Vite deciding to generate its own node_modules directory within the workspace rather than depending on a monorepo

I have organized a monorepo for a fullstack webapp with the directory structure outlined below: . ├── client │ ├── index.html │ ├── package.json │ ├── src │ └── vite.config.ts ├── node_modules ├── p ...

Establish the editor's starting state

Currently, I am utilizing lexical and aiming to establish initial text for the editor. At the moment, my approach involves hardcoding the initial text, but it seems I cannot simply pass a String as anticipated. Instead, the format required is JSON. Hence ...

Ways to eliminate undesired margin

I am struggling with formatting an HTML list into columns and I can't seem to remove the space between each column. It's frustrating because I want the list to display like rows, without any spacing or at least the ability to control the size of ...

JavaScript: Changing the names of all object keys

As a beginner, I am struggling to rename some objects in my key using a map function. Below is my current array: "platforms": [ { "id": 6, "name": "PC (Microsoft Windows)" }, { "id": 11, "na ...

Mastering the Art of Identifying the Direct Ascendant of the <

<div id="scriptparent"> <script type="text/javascript"> $( /* choose the <div> above this <script> code block without using any identifying attributes */ ) </script> </div> In my code, there is a <sc ...

Align the subtext to the right and center it vertically within a Bootstrap dropdown menu item

Is there a way to vertically align small captions on the right side of a dropdown menu, next to each item's text? The issue is that in the example below, the numbers are not properly aligned. https://i.stack.imgur.com/NZigW.png The numbers 123 and 1 ...

Changing the data type of a column in an Excel file from XLSX to

I am currently working with the XLSX npm package and attempting to download a sample Excel file, add some data to it, and then upload it back. The fields in the file include MOBILE NUMBER, DATE, TIME, and NAME. When I upload the file, the values for the DA ...

Using Django, CSS, and Javascript, create a dynamic HTML form that shows or hides a text field based on the selection

How can I hide a text field in my Django form until a user selects a checkbox? I am a beginner in Django and web applications, so I don't know what to search for or where to start. Any guidance would be appreciated. Here is the solution I came up wi ...

Guide to Embedding a SQL Table into an HTML Table

I need to set up a table within my current webpage to showcase a list of movies along with their genres. Welcome to my Movies page. The index.php file contains all the necessary database credentials and establishes the connection. <?php session_start( ...

Implementing Alloy-Script/Javascript in dynamically loaded JSP files

I have been loading various JSPs dynamically using an Ajax call, but after the JSP is loaded, none of the JavaScript inside seems to be working. I suspect this is because the script has not been parsed yet. To address this issue, I came across the "aui-pa ...

Encountering an issue while attempting to send an image through JavaScript, jQuery, and PHP

I'm currently attempting to upload an image using JavaScript/jQuery, but I am unsure of how to retrieve the image in order to send it to a server (PHP). I have a form containing all the necessary information that I want to save in MySQL, and I use jQu ...

Intermittent AJAX 403 Forbidden errors occur from time to time

My goal here is to validate whether a username is already taken in real-time as the user types, triggering an AJAX call on keyup event to check if it's available. If the username is taken, the input field will be highlighted in red. However, I've ...