Conceal the activated dropdown menu (toggle)

My code is functioning well, however there is a slight issue with the submenus. When I click on submenu A it opens perfectly, but if I then click on submenu B, A remains open and now both are displayed. I would like for B to close automatically when I click on A.

$(document).ready(function() {
  $('.submenu').hide();
  $("li:has(ul)").click(function() {
    $("ul", this).toggle('slow');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="link">Menu</a></li>
  <li><a href="link">Menu</a></li>
  <li>
    <ul class="submenu">
      <li><a href="link">Menu</a></li>
      <li><a href="link">Menu</a></li>
    </ul>
  </li>
  <li>
    <ul class="submenu">
      <li><a href="link">Menu</a></li>
      <li><a href="link">Menu</a></li>
    </ul>
  </li>
  <li><a href="link">Menu</a></li>
</ul>

Answer №1

To ensure proper functionality, insert $('.submenu').hide(); within your click event:

$(document).ready(function() {
    $('.submenu').hide();
    $("li:has(ul)").click(function() {
    $('.submenu').hide();
        $("ul", this).toggle('slow');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li><a href="#">Menu</a></li>
    <li><a href="#">Menu</a></li>
    <li>
        <ul class="submenu">
            <li><a href="#">Menu</a></li>
            <li><a href="#">Menu</a></li>
        </ul>
    </li>
    <li>
        <ul class="submenu">
            <li><a href="#">Menu</a></li>
            <li><a href="#">Menu</a></li>
        </ul>
    </li>
    <li><a href="#">Menu</a></li>
</ul>

Answer №2

Insert the following code into the click function:

$('ul li:has(ul)').not(this).find('.submenu:visible').toggle('slow');

$(document).ready(function() {
  $('.submenu').hide();
  $("li:has(ul)").click(function() {
    $('ul li:has(ul)').not(this).find('.submenu:visible').toggle('slow');
    $("ul", this).toggle('slow');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="link">Menu</a></li>
  <li><a href="link">Menu</a></li>
  <li>A
    <ul class="submenu">
      <li><a href="link">Menu</a></li>
      <li><a href="link">Menu</a></li>
    </ul>
  </li>
  <li>B
    <ul class="submenu">
      <li><a href="link">Menu</a></li>
      <li><a href="link">Menu</a></li>
    </ul>
  </li>
  <li><a href="link">Menu</a></li>
</ul>

Answer №3

You can implement the following code snippet:

$(this).siblings().children(".submenu:visible").toggle('slow');

Here is an example of how you can use it in your code:

$(document).ready(function() {
  $('.submenu').hide();
  $("li:has(ul)").click(function() {
    $(this).siblings().children(".submenu:visible").toggle('slow');
    $("ul", this).toggle('slow');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#">Menu</a></li>
  <li><a href="#">Menu</a></li>
  <li>A
    <ul class="submenu">
      <li><a href="#">Menu</a></li>
      <li><a href="#">Menu</a></li>
    </ul>
  </li>
  <li>B
    <ul class="submenu">
      <li><a href="#">Menu</a></li>
      <li><a href="#">Menu</a></li>
    </ul>
  </li>
  <li><a href="#">Menu</a></li>
</ul>

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

Rails vertical scrolling feature for Ruby developers

I'm in need of a vertical slider for my website. I am currently using Ruby 4.0 and have been utilizing the code snippet below to create a horizontal slider: <%= f.range_field :value, :min => 0, :max => 250 %> However, I want the slider b ...

"Conceal or reveal content with a toggle

Struggling to implement a simple hide and reveal effect in my JavaScript learning journey. Currently, the effect is only cancelled by clicking on another div with the same reference. Take a look at my JavaScript code: var $ = jQuery; $(document).ready(f ...

Is the spacing of the indicators on the bootstrap carousel uneven?

I'm stuck here and trying to figure out why the distance between the bootstrap carousel indicators is not equal. https://i.sstatic.net/n2MQm.jpg If you look at the image, you can see the uneven spacing between the 1st and 2nd indicators. #carou ...

Unable to resolve the issue with ExpressPeerServer not being recognized as a function in server.js

I'm facing an issue with the peer.js library in my npm project. I have successfully installed it, but when I try to use it in my server.js file, I get an error saying that peerServer is not a function. const express = require('express'); con ...

Looking for a solution to split barcode data across two text fields

I am looking to enhance my data input process by utilizing a barcode scanner in conjunction with JQuery. The barcode scanner I have reads both the serial number and model name of each product, but currently displays them together in one text field. Is ther ...

Incorporating Checkbox Value into Textbox with classic ASP and jQuery

Here is a glimpse of the code I've written: response.write "<th align=left><font size=2>" response.write "1. <input type=checkbox class='checkboxes' value='ORG'>Organization" response.write "</font> ...

What is the best way to add an Angular directive to ever-changing HTML content?

When creating dynamic HTML content, I am using the mark tag to highlight text. Depending on a condition, I want to apply one of two styles. To specify a CSS class, I can do it this way: <mark class='selected'> However, when trying to use ...

The Sizzle.js error, "Uncaught TypeError: undefined (reading 'expr')," is causing some trouble

$.expr[':'].containsCaseInsensitive = function (n, i, m) { return jQuery(n).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0; }; .expr is not recognized. To ensure it's defined, I included a CDN link below: <script src=&qu ...

Check that EACH radio button has been either selected or left unselected when the button is clicked

I'm still learning Javascript and currently working on a function triggered by a button click. My goal is to display an alert if NONE of the radio buttons have been selected, regardless of whether they are "Yes" or "No." If ALL radio buttons have been ...

Tips for checking a worldwide event tracker in VueJS

Learn how to implement a global event bus in VueJS with this insightful article. Instead of the conventional method of using an event bus defined in a separate file, the article introduces an alternative approach: import Vue from 'vue'; const E ...

Is it possible to import SVG files and inline them in Angular?

Behold, an SVG Circle: <svg viewBox="0 0 104 104"> <circle cx="52" cy="52" r="50" stroke="#003EFF" stroke-width="4" fill="#00FF98" /> </svg> The Angular Project imports it in this manner: import circle from './circle.svg'; ...

Unable to generate a select element using the JSON data retrieved from an Ajax request

After making an AJAX call to fetch some JSON objects, I successfully retrieve them. However, I encountered an issue while trying to generate a select element from the returned JSON - it doesn't seem to create one. This is what my JavaScript looks lik ...

If no other columns are present, ensure a column with a width of 9 fills the entire width

While working with Foundation 6, I encountered a situation where I had a large-3 column next to a large-9 column. The issue was that sometimes the large-3 column might not be present. In such cases, I wanted the remaining column to expand and fill up the ...

A surprise awaits in IE with the unusual appearance of a div display

body { background: #9cdcf9 url(/images/left_cloud.png) bottom left no-repeat; font-family:\"Trebuchet MS\"; padding:0; margin:0; border:0; } #cloud-container { width: 100%; background: url(/images/right_cloud.png) bott ...

Obtain an indeterminate value from a variable

My situation involves a dynamic variable assigned from a service, requiring a real-time calculator to update another variable using its value. Below is the relevant code snippet: $scope.getSubTotalSCTax = function(){ TableService.checkOut('SubTo ...

An empty canvas with jQuery being added

After successfully integrating jQuery into my PHP script, I encountered an issue where the page goes blank once the jQuery script is added. Below is the code snippet causing the problem: function site_header() { echo "<html dir=\"rtl\"&g ...

Troubleshooting: Resolving the "npm ERR! missing script: start" Issue

I'm encountering the error below: npm ERR! missing script: start npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\..\AppData\Roaming\npm-cache\_logs\2019-04-27T18_02_39_6 60Z-debug.log Th ...

Retrieving Browser URL using Node.js

Currently, I am trying to extract the browser URL from a user who has integrated my external JavaScript file into their website. The process involves them including the JS file, which triggers an Ajax call using jQuery to communicate with my Node server. ...

Typescript having issues compiling to commonjs/es2015 accurately

I currently have Node v14.5.0 installed and I'm using ts-node-dev in my development environment However, I am encountering an error every time I try to compile to JS. Initially, I attempted with the following tsconfig: "target": "es5& ...

Guide on utilizing jQuery to read and insert a local HTML file directly into a textarea

What is the best way to load a local HTML file in raw format and insert it into a textarea using jQuery version 1.3? ...