Is there a way for me to automatically close other menus when the current menu is open using slideToggle?

Seeking assistance with enhancing the navigation functionality.

How can I ensure that when a user clicks on a menu item, any other open menus are closed and the active class is removed from them?

The current navigation setup meets my requirements except for this specific aspect.

Any guidance or support on this matter would be greatly appreciated.

Thank you!

$(document).ready(function() {

  $('.navigationV1 ul.top-level-menu .label').on('click', function() {
    // Toggle top nav links
    $(this).siblings('.drop-down-menu').slideToggle();
    $(this).toggleClass('active');
  });

});
.active {
  background-color: #666;
}

.drop-down-menu {
  display: none;
}
<div class="navigationV1 top-level-menu label">

  <div class="descendant-links-container">
    <ul class="top-level-menu">

      <li>
        <a class="label">Menu 1</a>

        <ul class="drop-down-menu">
          <li>
            <a>Drop-down-menu 1</a>
          </li>
        </ul>
      </li>

      <li>
        <a class="label">Menu 2</a>
      </li>

      <li>
        <a class="label">Menu 3</a>
        <ul class="drop-down-menu">
          <li>
            <a>Drop-down-menu 2</a>
          </li>
        </ul>
      </li>
    </ul>
  </div>
</div>

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

Answer №1

To begin, it is important to locate any open menus and close them before proceeding to open the new menu:

$(document).ready(function() {

    $('.navigationV1 ul.top-level-menu .label').on('click', function() {
        // Closing already opened menus
        if (!$(this).hasClass('active')) {
            $('.label.active').removeClass('active').siblings('.drop-down-menu').slideUp();
        }
        // Toggling top navigation links
        $(this).siblings('.drop-down-menu').slideToggle();
        $(this).toggleClass('active');
    });

});

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

Detecting which item is selected when the tab key is pressed using Javascript and jQuery

I'm having trouble figuring out which element is currently selected or focused when using the tab key. I want to trigger a function when the enter key is pressed on the currently selected item. The code should be pretty straightforward, but my proble ...

When you click on a table row, it will trigger the opening of a stylish F

My goal is to trigger a fancybox when clicking anywhere on a table row. However, upon clicking a row, I am encountering an error message in the Firebug console: too much recursion Line 2925 Below is the HTML code I am using: <table id="allItem ...

Exploring arrays with JavaScript and reading objects within them

Recently, I received assistance from a member of StackOverflow regarding AJAX calls. However, I have encountered a problem now. The code consists of a loop that sends requests to multiple REST APIs and saves the results in an array as objects. The issue ...

How can I position the title above the navigation links in a Bootstrap navbar?

Is there a way to position a bootstrap header above the bootstrap navigation menu? I envision an initial 250px height header with the nav-brand placed above the nav menu, both centered. As the user scrolls, the header should shrink to match the default boo ...

Can we execute a function once a mandatory field in a form has been validated successfully?

Looking for a way to execute a function after validating required inputs in a form before submission. Any suggestions? And I'm specifically not using jQuery, but Angular ...

Relocating JavaScript scripts to an external file on a webpage served by Node.js' Express

When using Express, I have a route that returns an HTML page like so: app.get('/', function(req, res){ return res.sendFile(path.resolve(__dirname + '/views/index.html')); }); This index.html file contains multiple scripts within t ...

You can tab through form input boxes on an Adobe Muse website, but they cannot be clicked

Lately, I created a small website using Adobe Muse and incorporated their form widget. However, I haven't altered any of the default settings and now the input boxes are not clickable. The only way to interact with them is by tabbing through. How can ...

Error: Attempting to access 'toString' property on an undefined value - redis

const updateLeaderboards = async () => { try { const users = await User.findAll(); const leaderboardData = []; users.forEach((user) => { // Add user data to the leaderboardData array in the required format leaderboardData.p ...

How to Exclude ress.css in Vuetify.js

How can I prevent ress.css from conflicting with Bootstrap and my custom styles in Vuetify? I attempted to remove it from the Vuetify directory within node_modules, but that did not resolve the issue. ...

Having trouble saving post data using ajax in django

I am encountering an issue with saving my partial '_dim' while viewing the main template 'sheet_form_create.html'. Every time I try to post the data for my '_dim' partial, I receive an error. Any assistance would be greatly ap ...

What is the best way to create custom middleware in Express to promptly respond with a 413 status code if the incoming request exceeds a

It seems that the current setup is not returning any response. What's strange is that the debug logger indicates POST /ServiceName 413 2ms var maxSize = 1000*1000; module.exports = function (req, res, next) { var size = req.headers['content-l ...

How to implement a for loop within a Vue.js method

Within Vuejs, I have a method that updates multiple variables based on user selection. methods: { updateChart(){ this.chart1.series[1].data = [this.$store.state.selectedcities[0].value[1]]; this.chart1.series[2].data = [this.$store.state.selecte ...

Styling your sidebar with CSS and Bootstrap to accommodate dynamic content with varying heights

How can I adjust the height of my sidebar block to match the height of the sidebar main block and the content block? Check out this example image I created: https://i.sstatic.net/qFIxe.png I'm currently using Bootstrap 4 and have experimented with ...

"The value of a variable in jQuery's 'animate' function can be dynamically adjusted

Looking to smoothly animate a variable using jquery. For example: Starting with a variable value of 1, we want it to reach 10 after 5 seconds. The transition should be smooth and increase gradually. I hope this clarifies what I am trying to achieve. Tha ...

Is there a limit to the number of else if statements I can use? The final else statement

How can I enhance this code snippet? The last else if statement is not working, despite my efforts to fix it. var selectedDntTyp = $("#donationTypDD"); if (selectedDntTyp.length > 0) var DropInitValue = selectedDntTyp.val(); if(DropInitValue == &apos ...

implementing a button's decrease and increase functionality in JavaScript

Whenever the button is clicked, it changes its color to red. Additionally, a counter increments with each click. However, I want the counter to be dynamic so that when the button is unclicked, the counter decreases as well. Unfortunately, I am facing diffi ...

Click automatically upon loading the page

I'm looking for help to automatically click a button after the page loads. I currently have to manually click the "Buy the basket" button, but I am not familiar with coding at all. I need a fully ready code that can automate this process for me. Can s ...

Building/Deleting the Vue Component using text search

In my App.vue file, I have the following setup: <template> <div id="app"> <input type="text" v-model="term"> <hello-world text="Button 1" v-if="term === ''"></hello-world> <hello-world ...

The variable is only recognized within the function and not outside of it

Seeking assistance as a newcomer in debugging and implementing code, I have been trying various approaches to pass a base64string into JotForms for generating images in PDF format. Below is the screenshot of the error encountered. View error here The foll ...

Changing model to array in mvc 3

I have a model that I would like to convert into an array by clicking on a button to execute a JavaScript function. The function will then send the array to a controller that will either read and parse the data as JSON or simply as a Model. For example: ...