Is there a way to automatically close one menu when another is opened by clicking?

When all other search results have failed to solve my issue, I resort to posting my own question.

My problem involves opening hidden submenus in a website's main menu. However, when I open multiple submenus, they just stack above each other. Ideally, I want only one submenu to be open at a time, meaning that when I open a new one, the previously opened one should close.

jQuery(document).ready(function($) {
  $(".clickSlide > ul").hide();
  $(".clickSlide").click(function() {
    $(this).children("ul").stop(true, true).slideToggle("fast"),
      $(this).toggleClass("dropdown-active");
  });
});
<ul id="menu-sidhuvud-e-butik-vanster" class="menu">
  <li class="clickSlide menu-item menu-item-has-children"><a>Parent 1</a>
    <ul class="sub-menu" style="display: none;">
      <li class="menu-item-has-children menu-item-1947"><a href="#">Sub parent</a>
        <ul class="sub-menu">
          <li class="menu-item-1948"><a href="#">Link object</a></li>
          <li class="menu-item-2224"><a href="#">Link object</a></li>
        </ul>
      </li>
    </ul>
  </li>

  <li class="clickSlide menu-item menu-item-has-children"><a>Parent 3</a>
    <ul class="sub-menu" style="display: none;">
      <li class="menu-item-has-children menu-item-1947"><a href="#">Sub parent</a>
        <ul class="sub-menu">
          <li class="menu-item-1948"><a href="#">Link object</a></li>
          <li class="menu-item-2224"><a href="#">Link object</a></li>
        </ul>
      </li>
    </ul>
  </li>

  <li class="clickSlide menu-item menu-item-has-children"><a>Parent</a>
    <ul class="sub-menu" style="display: none;">
      <li class="menu-item-has-children menu-item-1947"><a href="#">Sub parent</a>
        <ul class="sub-menu">
          <li class="menu-item-1948"><a href="#">Link object</a></li>
          <li class="menu-item-2224"><a href="#">Link object</a></li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Does anyone have any suggestions? I am quite new to JS and would appreciate any guidance.

Thank you for your help!

Answer №1

If you already have a formula in your code for this task, all you need to do is make sure to toggle the .hide() function on every other element that was not clicked.

$(this).siblings().children("ul").hide("fast")

The line above accomplishes exactly that by selecting all siblings and hiding their children with ul tags.

jQuery(document).ready(function ($) {
  $(".clickSlide > ul").hide();
  $(".clickSlide").click(function () {
    $(this).siblings().children("ul").hide("fast")
    $(this).children("ul").stop(true, true).slideToggle("fast"),  
    $(this).toggleClass("dropdown-active");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="menu-sidhuvud-e-butik-vanster" class="menu">

  <li class="clickSlide menu-item menu-item-has-children"><a>Parent 1</a>
    <ul class="sub-menu" style="display: none;">
      <li class="menu-item-has-children menu-item-1947"><a href="#">Sub parent</a>
        <ul class="sub-menu">
          <li class="menu-item-1948"><a href="#">Link object</a></li>
          <li class="menu-item-2224"><a href="#">Link object</a></li>
        </ul>
      </li>
    </ul>
  </li>

  <li class="clickSlide menu-item menu-item-has-children"><a>Parent 3</a>
    <ul class="sub-menu" style="display: none;">
      <li class="menu-item-has-children menu-item-1947"><a href="#">Sub parent</a>
        <ul class="sub-menu">
          <li class="menu-item-1948"><a href="#">Link object</a></li>
          <li class="menu-item-2224"><a href="#">Link object</a></li>
        </ul>
      </li>
    </ul>
  </li>

  <li class="clickSlide menu-item menu-item-has-children"><a>Parent</a>
    <ul class="sub-menu" style="display: none;">
      <li class="menu-item-has-children menu-item-1947"><a href="#">Sub parent</a>
        <ul class="sub-menu">
          <li class="menu-item-1948"><a href="#">Link object</a></li>
          <li class="menu-item-2224"><a href="#">Link object</a></li>
        </ul>
      </li>
    </ul>
  </li>

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

Prevent refreshing Google Maps when changing routes in AngularJS

Utilizing a Google map as the background for my website adds a unique visual element to the data displayed on different routes. However, I have encountered an issue where the map reloads with every route change, resulting in an unsightly flash of white tha ...

Displaying outcomes in dialog box when button is pressed

I am working on a website where I want to enhance the user experience by displaying output in a dialogue box upon click. The current setup involves the user selecting a vendor and time duration, with the results appearing below the Submit button. However, ...

Unique Text: "Personalized marker/pin for interactive map feature"

Looking to create a custom image map marker/pin with a unique bottom design resembling a union shape using CSS and Vue.js. I've attempted it myself but haven't been able to achieve the exact look as shown in the reference image. Any advice or ass ...

Tips for stopping the textarea from moving around as you type and avoid it hitting the bottom of the page: Utilize JQuery and

As I type into the auto-sizing textarea, the text runs to the bottom of the page and causes it to dance uncontrollably with each key press. This forces me to constantly scroll down to see what's happening. How can I prevent this page dancing and keep ...

How can I automatically disable certain checkboxes when a specific radio button is selected?

Looking to disable certain checkboxes when a specific radio button is selected. For instance, selecting the first radio button with the id="pz1" should disable checkboxes with matching id values from the thisToppings array. Each radio button cor ...

What is the best location to place an HTML wrapper element within a React Project?

Just diving into the world of React, I've embarked on a simple project with bootstrap My goal is to reuse a specific HTML structure: <div className="container"> <div className="row"> <div className="col-lg-8 col-md-10 mx-auto"&g ...

Strategies for dynamically altering Vue component props using JavaScript

for instance: <body> <div id="app"> <ro-weview id="wv" src="http://google.com"></ro-weview> </div> <script> (function () { Vue.component("ro-webview", { props: ["src"], template: ` <input type="t ...

Do we always need to incorporate components in Vue.js, even if there are no plans for reuse?

I've been pondering this question for some time now: is it necessary for every component to be reusable? Consider a scenario where we have HTML, CSS, and JavaScript that cannot be reused. For instance, a CRUD table designed specifically for managing u ...

Unclear value of button when being passed

In my Welcome.html file, I am attempting to send the value of a button to a function that simply logs that value. This function is located in a functions class that has been imported into my welcome.ts file. <ion-content padding id="page1"> <h1 ...

React Native Header Icon Not Showing on the Left Side

I'm brand new to react and currently working on a project where navigation is done through a hamburger menu. I haven't encountered any errors in my code, but for some reason, the hamburger menu icon isn't displaying as expected. Interestingl ...

The proper way to insert data in JavaScript and PHP

Hello. I have a new function to add a row in my form. However, I recently added a second input field and I am unsure of how to correctly insert it. Below is my JavaScript code: <script type="text/javascript" src="jquery.js"></script> <scri ...

Maintaining a consistent style input until it is modified

I'm currently dealing with this code (continuing from a previous question): input[type=submit]:focus { background-color: yellow; outline: none; } The issue I'm facing is that when I click anywhere else on the screen, the background color go ...

Building a dynamic tab menu using JavaScript: A step-by-step guide

In order to generate dynamic tab menus with JavaScript, I am seeking a solution that does not rely on jQuery as it may not be supported by all mobile devices. Any advice for replicating the same functionality using pure JavaScript would be greatly apprec ...

Multiple ngFor loops causing only the final item to be displayed in the inner loop

Can someone assist with my code where I loop through firebase RTDB reference to retrieve a list and then use those results in a subsequent firestore query? The console logs the correct data, but my code only displays the last item in the loop inside ngFor. ...

What's the best way to create an onclick event for a li element that includes a pseudo-element ::before

I have successfully created a Timeline using HTML and CSS elements. The visual result is as follows: My goal is to enable users to click on the second circle, triggering a color change in the line that connects the first and second circles. This color tra ...

The functionality of window.localStorage.removeItem seems to be malfunctioning when used within an $http

Currently, I am sending a post request to my web service and upon successful completion, I am attempting to remove a token from local storage. Here is the code snippet: $http.post("MyService/MyAction").success(function (res) { if ( ...

Creating a debounce functionality by isolating it from a keydown event listener

I have a table with selectable rows using up and down arrows. When a row is selected, an ajax call is made to fetch the record. To prevent users from spamming ajax requests, I implemented a debounce function called from a directive triggered by a keydown ...

Troubleshooting module not being found with rekuire, requirish, or rfr in resolving relative require problem in nodejs

Looking to steer clear of the complicated relative path problem detailed here by opting for one of the suggested solutions. I've found three similar libraries that could help: rekuire node-rfr aka Require from Root requirish I've experimented ...

Each time guildMemberAdd is triggered in Discord.js, it may not run consistently

At times, I am left baffled by the inconsistency in behavior of this code. Sometimes it works like a charm, while other times it refuses to add people for hours on end, only to randomly start working again. Any suggestions on how I can resolve this issue? ...

Incorporate a progress bar into the Material-UI table design

I have the following example of a Material-UI table: import React from "react"; import clsx from "clsx"; import { createStyles, lighten, makeStyles, Theme } from "@material-ui/core/styles"; import Table from "@mat ...