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

Each time the page is reloaded, the Ajax call is triggered, resulting in duplicated

When I visit my homepage, one of the components on the page looks like this: import React, {Component} from 'react'; class BlogPostsWidget extends Component { render() { $.ajax({ type: "GET", url: 'https://example.com/wp- ...

The Microsoft.Azure.WebJobs.Script encountered an issue while attempting to cast an object of type 'System.String' to type 'Microsoft.AspNetCore.Http.HttpRequest' during the return process

I recently encountered an issue with my Azure Function written in JS that is triggered by the Service Bus and generates files to Blob Storage. When attempting to return an HTTP result, I received the following error message: System.Private.CoreLib: Except ...

Is JQuery the ultimate solution for creating a dynamic multi-language website?

Embarking on a new project that requires support for multiple languages. My plan is to create a jQuery/AJAX based application with all the code in jQuery, simply calling JSONs for data. What would be the most effective approach for implementing multi-lan ...

Properly aligning text with checkboxes using HTML/CSS and tags like <span> or <div>

My goal is to have the text displayed as a block in alignment with the checkbox, adjusting based on the sidebar's width. For reference: Current Layout Preferred Layout I have shared the code on CodePen (taking into account screen resolution and wi ...

Adding new options to a multi-select dropdown in Vue.js when fetching data using an

Greetings! I've been utilizing a modified wrapper to manage a multiple select for vue.js. My goal is to change the value of 'this' inside the vue component. Below is the snippet of my code. <select2-multiple :options="car_options" v-mode ...

Using NodeJS to retrieve the mean price from the OPSkins pricelist

Is there a way to calculate the average price of every skin listed in this document? I'm wondering how one would go about using the dates and prices in order to determine the 60-day average price. My approach would involve extracting the data from t ...

Next.js encountered an API resolution issue while uploading a file, resulting in no response being

Even though my code is functioning properly, a warning appears in the console: The API call was resolved without sending any response for /api/image-upload This particular endpoint is responsible for uploading an image to Digital Ocean's object sto ...

Changing ch to Px in CSS

Important Notes: I have exhaustively explored all the questions and answers related to this particular topic. The question I have is very straightforward: How many pixels are equivalent to 1 character? Here's a sample of my code - code Related Sear ...

Exploring the Modularity of Post Requests with Node.js, Express 4.0, and Mongoose

Currently, I am immersed in a project that involves utilizing the mean stack. As part of the setup process for the client-side, I am rigorously testing my routes using Postman. My objective is to execute a post request to retrieve a specific user and anot ...

Find the index of the element that was clicked by utilizing pure JavaScript

I am struggling to find the index of the element that was clicked. Can anyone help me with this? for (i = 0; i < document.getElementById('my_div').children.length; i++) { document.getElementById('my_div').children[i].onclick = f ...

Guide on how to trigger the opening of a side panel with a button click in Vue.js

Embarking on my first Vue app development journey, I find myself in need of guidance on how to trigger the opening of a panel by clicking a button within the header. Starting off with a simple HTML template, my goal is to add some interactivity upon click ...

What is the best method for adding files to JSZip from a remote URL?

Is it possible to load files into a Zip folder from a specified URL? For example: var zip = new JSZip(); zip.file("file.txt", "/site.net/files/file.txt"); Update I am following this example: I attempted the code provided but it was unsuccessful. I do ...

Non-responsive Click Event on Dynamically Created Div Class

I am facing some uncertainty in approaching this problem. In the HTML, I have created buttons with additional data attributes. These buttons are assigned a class name of roleBtn. When clicked, they trigger the jQuery function called roleBtnClicked, which ...

I am puzzled as to why my ajax script is giving me a 404 error even though the URL appears to be correct

Even though it's not a cross-domain problem, Ajax is returning a 404 error code. In my TIZEN Web application project, I am trying to make an ajax request to a WebService that contains functions necessary for the project. Initially, the xhr.status was ...

Mastering the Art of Crafting an Effortless Slide Showcase

I have created a carousel that works fine except for one issue: when I reach the last image or go back from the first image, I want the image to be displayed. For example, when you click the right arrow after reaching the last image, it should show the fir ...

Tips for transferring localstorage values from the view to the controller in order to utilize them as a PHP variable in a separate view

How can I pass the value from local storage as a PHP variable when using location.href in the controller after clicking a button? In the view: echo Html::button('Proceed', [ 'onclick' => " var dataVal = localStorage.g ...

Finding the value of an input without having to submit it first and searching for it within a datalist

> Here is an example of HTML code <label>Person</label> <input name="PersonID" type="text" id="PersonID"> <label>Car Plate Number</label> <input name="PersonsCarPlateNumber" list="PersonsCarPlateNumbe ...

"Sending an array in a POST request using Javascript and processing it on the server

I am trying to use ajax to send an array. Let's say the array looks like this: var anotherOne = 'anotherOneData'; var documents = ['banana', 'apple', 'monkey']; I successfully sent both a normal value and an a ...

What are some techniques for styling a field when the div id is not specified?

I need to customize a data field within a table, but I am unable to locate or identify its div ID. Here is the page source: <tbody> <tr> <td style="font-size:12px; text-align:center;" name=""> <div sty ...

Offering fields for modules, main, and browser that meet the needs of ESM, CommonJS, and bundlers

I have upgraded a number of my published npm packages to include both commonjs and esm builds. Some of these packages are meant for use in both node and the browser, and they are all compiled using webpack or rollup. Additionally, all of them are written i ...