Activate Jquery to display the submenu when clicked and conceal any other open submenus at the same time

I'm trying to create a responsive menu with menus and submenus using JQuery. However, as a newbie to JQuery, I'm struggling to hide a previous submenu when displaying another one.

Here's the CodePen link

Below is the HTML code:

<nav class="products">
    <ul>
        <li class="brown link-menu"><a href="#">wine essentials</a>
            <div class="sub-menu">
                <div class="content-sub-menu">
                    <ul class="sub-menu-list">
                        <li class="link-subcat"><a href="#" class="menu-subcat-link">standard</a></li>
                        <li class="link-subcat"><a href="#" class="menu-subcat-link">premium</a></li>
                        <li class="link-subcat"><a href="#" class="menu-subcat-link">super premium</a></li>
                        <li class="link-subcat"><a href="#" class="menu-subcat-link">ultra premium</a></li>
                    </ul>
                </div>
            </div>
        </li>
        <li class="pink link-menu"><a href="#">wine selective & prestige</a>
            <div class="sub-menu">
                <div class="content-sub-menu">
                    <ul class="sub-menu-list">
                        <li class="link-subcat"><a href="#" class="menu-subcat-link">standard</a></li>
                        <li class="link-subcat"><a href="#" class="menu-subcat-link">premium</a></li>
                        <li class="link-subcat"><a href="#" class="menu-subcat-link">super premium</a></li>
                        <li class="link-subcat"><a href="#" class="menu-subcat-link">ultra premium</a></li>
                    </ul>
                </div>
            </div>
        </li>
        <li class="green link-menu"><a href="#">master distillers</a>
            <div class="sub-menu">
                <div class="content-sub-menu">
                    <ul class="sub-menu-list">
                        <li class="link-subcat"><a href="#" class="menu-subcat-link">standard</a></li>
                        <li class="link-subcat"><a href="#" class="menu-subcat-link">premium</a></li>
                        <li class="link-subcat"><a href="#" class="menu-subcat-link">super premium</a></li>
                        <li class="link-subcat"><a href="#" class="menu-subcat-link">ultra premium</a></li>
                    </ul>
                </div>
            </div>
        </li>
    </ul>
</nav>

Here is the SCSS code:

nav.products {
  ul {
    li.brown {
      border-left: 10px solid #a09484;
    }
    li.pink {
      border-left: 10px solid #9d7b8c;
    }
    li.green {
      border-left: 10px solid #558d80;
    }
    li {
      border-bottom: none;
      padding: 1em 0;
      margin-bottom: .2em;
      a {} .sub-menu {
        height: 0;
        overflow: hidden;
        .content-sub-menu {
          -moz-transform: translateY(-100%);
          -ms-transform: translateY(-100%);
          -webkit-transform: translateY(-100%);
          transform: translateY(-100%);
          -webkit-transition: transform 0.3s ease-in-out;
          -o-transition: transform 0.3s ease-in-out;
          transition: transform 0.3s ease-in-out;
          ul.sub-menu-list {
            padding-left: 1em;
            li {
              font-size: 1em;
              margin-bottom: 0;
              a {}
            }
          }
        }
      }
      &.current {
        .content-sub-menu {
          -moz-transform: translateY(0%);
          -ms-transform: translateY(0%);
          -webkit-transform: translateY(0%);
          transform: translateY(0%);
        }
        /*DROPDOWNS*/
        .sub-menu {
          height: 100%;
        }
        /*DROPDOWNS END*/
      }
    }
  }
}
nav.products ul li.current .sub-menu {
  height: 100%;
}

And this is the script used to display the submenus:

$('.products ul li').click(function(e) {
    $(this).toggleClass('current');
});

Answer №1

$('.items ul li').click(function(e) {
   $('.active').removeClass('.active');
   $(this).addClass('active');
});

Give it a shot. This method finds any active class on the page, removes it, and adds the class to the clicked element.

Answer №2

Simply remove the 'current' class from all menu items before toggling with ease.

$('.products ul li').click(function(e) {
  $('.products ul li').removeClass('current');
  $(this).toggleClass('current');
});

Check out this example in action: http://codepen.io/anon/pen/NRPLRN

Answer №3

To implement the desired functionality, it is important to first eliminate the .current class from the li element before proceeding with the toggling of the class.

$('.products ul li').click(function(e) {
     $('.products ul li.current').removeClass('current');
     $(this).toggleClass('current');
});

Check out the Updated Code on CodePen

Answer №4

To conceal sub-menus that have been opened before, the "current" class must be eliminated from them.

$('.items ul li').click(function(e) {
   $('.items ul li').not($(this)).removeClass('current');

  $(this).toggleClass('current');
});

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

``In JavaScript, the ternary conditional operator is a useful

I am looking to implement the following logic using a JavaScript ternary operation. Do you think it's feasible? condition1 ? console.log("condition1 pass") : condition2 ? console.log("condition2 pass") : console.log("It is different"); ...

Updating Tailwind CSS to accommodate older web browsers by converting modern rgba() notation to be browser-compatible

I am facing a challenge with Tailwind CSS v3+ as it builds colors into the rgb space/color notation that is not compatible with an older browser (Safari 11) that my web app now needs to support. For example, rgb(163 160 158 / var(--tw-bg-opacity) The iss ...

Retrieve data from a Datatable using jQuery by dynamically generating a click event on a button

Looking to utilize jQuery for the first time, I'm facing an issue accessing the datatable contents upon clicking the erase button. Despite trying various methods, I keep receiving an undefined result. $(document).ready(function() { loadData() }); ...

Customizing material-ui styles within a nested component

I am looking to modify the position of the expandIcon in an ExpansionPanel by changing the right attribute: <ExpansionPanel> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <Typography className={classes.heading}&g ...

Issue with random pages where global header.php is not showing a specific image

I'm currently revamping a website that was originally developed using codeigniter. The backend is quite chaotic with no clear identifiers for anything. I recently updated the banner in the header.php file, adjusting the style to suit the requirements. ...

Change the state of items in a React component to either disabled or active depending on the active items list retrieved from the API

Obtained from the API, I have a collection of buttons that are displayed for filtering: For instance: button2 button4 button5 Assuming there are a total of 5 buttons. button1 and button3 are supposed to be in a disabled or inactive state (appearing ...

Trouble with AJAX POST request functionality outside of POSTMAN's scope

Attempting to send data via an AJAX request. Check out the code below: console.log(quote) $.ajax({ url: '{{ path('set_products_in_db') }}', type: 'POST', contentType: "application/json", ...

Using a jQuery modal to submit a button and update data in the window

In my current project, I have set up a jQuery modal that appears when the user clicks submit on a form. This modal serves as a confirmation window displaying all the data entered in the form. It contains two buttons - "Go" and "Cancel". If the user clicks ...

The functionality of the bootstrap grid system may vary depending on the size of the device being

I'm currently experiencing an unusual issue with Bootstrap. From what I understand, the bootstrap grid system is based on 12 units and is supposed to work seamlessly across various device sizes, such as iPhones. I have a simple banner comprised of 5 c ...

Prevent users from selecting elements on the mobile site

Hey there! I'm currently working on preventing users from selecting items on my mobile site. While I've been successful in doing so on a regular website using the CSS class below .unselectable { -moz-user-select: -moz-none; -khtml-user-s ...

The PopupControlExtender in ajaxToolkit seems to be malfunctioning when used with a textbox that has Tinymce

I recently built a website using ASP.NET, and I have a feature where a small tooltip appears on the right side of a text box when the user focuses on it. To achieve this, I am using the ajaxToolkit:PopupControlExtender in my code. <asp:TextBox ...

Tips for automatically inserting a "read more" link once text exceeds a certain character count

Currently utilizing an open-source code to fetch Google reviews, but facing an issue with long reviews. They are messing up the layout of my site. I need to limit the characters displayed for each review and provide an option for users to read the full rev ...

Creating a secure countdown timer on the server side: Best practices

I've developed a quiz application that features a countdown timer of 300 seconds for answering 10 questions. Once the time is up, the scores are sent to the server where they are compared with the answers and then stored. However, my main concern is t ...

Create dynamic cells for CSS grid using JavaScript

I have been manually generating grid cells in a specific pattern by copying and adjusting <div> elements. Although this method works, I am interested in creating an algorithm that can automatically generate the desired layout. The left box in the exa ...

"Assure that setTimeout will be executed within the then method in

Within an Immediately Invoked Function Expression (IFFE), I am returning a Promise. The first thing that is logged is first, followed by third, and then second. Despite having the setTimeout inside the then block, shouldn't everything within it be exe ...

Issue TS7053 occurs when trying to access any index of the target of a React.FormEvent<HTMLFormElement>

I've been working on adapting this tutorial to React and TypeScript. Here is the code snippet I have implemented for handling the onSubmit event: const handleSignUp = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); ...

Embedding Vue component into a traditional PHP/jQuery project

Currently, I have a large legacy web application that is primarily built using Codeigniter and jQuery. Our strategy moving forward involves gradually transitioning away from jQuery and incorporating Vuejs into the project instead. This process will involv ...

Here is a method to transform the JSON object into a string as demonstrated below:

Presented below is a JSON object: { "category": "music", "location": { "city": "Braga" }, "date": { "start": { "$gte": "2017-05-01T18:30:00.000Z" }, "end": { "$lt": "2017-05-12T18:30:00.000Z" } } } I am looking t ...

Display method JSONized

Looking for guidance on improving code efficiency and best practices. In my current project, I am working with a JSON Array structured like this: [ { "Date": "2014-07-16", "DiscPoint": "Description 1", "DisBy": "Person 1" ...

Prevent selection of future dates in JavaScript by using the user's chosen StartDate

Here is the code I currently have: var today = new Date().toISOString().split('T')[0]; document.getElementsByName("StartDate")[0].setAttribute('min', today); $('#StartDate').change(function myfunction() { var endDate = ...