Automatically closing any previously opened submenus when a new one is clicked

I am struggling with closing the previously clicked menu item when clicking on a new one in my vertical menu with submenus. Currently, all menus stay open. How can I achieve this?

Here is the HTML code:


  <div class="sidebar ">
     <div class="menu-layout">
         <ul>
            // Menu items and submenus go here
        </ul>
    </div>
</div>

This is the JavaScript code controlling the submenu behavior:


  <script>
    $('.sub-menu ul').hide();
    $(".sub-menu a").click(function () {
        $(this).parent(".sub-menu").children("ul").slideToggle("100");
        $(this).find(".right").toggleClass("fa-caret-up fa-caret-down");
    });
</script>

And here is the corresponding CSS:


  .menu-layout .first-level {
    margin-bottom: 9px;
    border-radius: 5%;
    padding: 2px 10px 2px 10px;
    line-height: 15px;
}

.second-level {
    margin-bottom: 9px;       
    padding: 2px 50px 2px 10px;
    line-height: 15px;
}

.menu-layout li a {
    color: white !important;
    font-size: 13px;
}

.menu-layout li a i {
    color: white;
    padding-left: 10px
}

.sidebar {
    position: fixed;
    top: 1px;
    width: 250px;
    height: calc(100% - 1px);
    border-bottom-left-radius: 20px;
    transition: all 0.3s ease;
    background-color:black;
    font-family: IRANSans;
    font-weight: 400;
}

Answer №1

Here is the updated code:

$(document).ready(function () {
    $(".sub-menu ul").hide();
    $(".sub-menu a").click(function () {
        $(".sub-menu ul").not(this).hide(); // Hide everything except for current item.
        $(this).parent(".sub-menu").children("ul").slideToggle("100");
        $(this).find(".right").toggleClass("fa-caret-up fa-caret-down");
    });
});

The CSS and HTML snippets have not been modified in this update.

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

Encountering an issue in Angular 8 where there is a difficulty in reading the property 'NODE_NDEBUG' when attempting to serve the application

An issue has been identified in the assert-plus library at ../node_modules/assert-plus/assert.js where it is encountering difficulties reading 'NODE_NDEBUG' from 'process.env', as highlighted in the code snippet below module.exports = ...

Enable Cursor Display in Readonly Input Fields

Consider this scenario: Setting an input field to .readOnly = true replaces the text cursor with a pointer arrow cursor, preventing users from entering or modifying the field. Interestingly, clicking into a readonly input field that already contains text s ...

Loading SVGs on the fly with Vue3 and Vite

Currently, I am in the process of transitioning my Vue2/Webpack application to Vue3/Vite. Here's an example of what works in Vue2/Webpack: <div v-html="require('!!html-loader!../../assets/icons/' + this.icon + '.svg')" ...

Can the memory consumption of a JavaScript variable be determined?

Currently focused on Frontend development with React and Javascript. I am eager to discover if there is a method to retrieve the memory usage of a JavaScript variable, especially for objects and non-primitive values. My investigation in Chrome Dev Tool d ...

Interact with an AngularJS model using an external script

I've exhausted all possible methods to activate the ng-model functions in my form. Utilizing the bootstrap datepicker, I need the ng-model value to update when a date is selected. Can someone please advise me on how to interact with the ng-model using ...

I've been struggling with my Create React app for the past two days, and it just won

When trying to create a React project using the command `npx create-react-app reactproject`, I encountered an error: npm ERR! code ENOENT npm ERR! syscall spawn C:\Users\SUJITKUMAR\Desktop npm ERR! path D:\WebDev\React npm ERR! ...

Can JavaScript and CSS be used to dynamically style textarea content as it is being typed by the user?

I am wondering if it is possible to apply styling to content in a textarea as a user inputs text. For instance: <textarea>abcdefghijklmnopqrstuvwxyz</textarea> Is there a way to highlight all the vowels in the textarea string above using jav ...

Is there a way to utilize nodemon without having to install it through npm?

I'm having trouble with my network not allowing me to use npm install. Is there another way for me to install and use nodemon? I've noticed that Node only runs after setting PATH variables on Windows. I attempted to set the path for nodemon, but ...

Modify the text field's color when it is in a disabled state

When the text field is disabled, I want to change its color. Below is the code I have written for enabled and disabled states. The style works correctly when the text field is enabled. const StyledTextField = styled(({ dir, ...other }) => <TextFiel ...

Employ jQuery to display a text box with a sliding motion upon hovering the mouse cursor over a specific area

Beginner inquiry about jQuery. Imagine I have a label on my webpage and I am looking to create a sliding effect for an input box when hovering over the label. Can anyone offer tips on utilizing jQuery to make this happen? ...

When designing responsive websites in Bootstrap 4, what is the preferred choice between using the class "container" or "container-fluid"?

When creating responsive designs, which is more effective to use - the .container class or the .container-fluid class? ...

Executing axios calls within other axios calls and altering state in React before all calls have completed

Currently, I am working on implementing nested axios calls to create the desired object by making multiple API requests. However, I am facing an issue where the state updates before all requests have finished, causing my table to populate entry by entry ...

Establish a buffering system for the <video> element

Currently, I am facing an issue with playing videos from a remote server as they take an extended amount of time to start. It appears that the entire video must be downloaded before playback begins. Is there a way to configure the videos so they can begi ...

Determining element visibility in React

Please refrain from flagging this as a duplicate. While it may be similar to other questions, I am specifically inquiring about the location to place the code, not how to write it. Here is the code I have and my goal is to determine which section is curre ...

My custom CSS being overridden by Bootstrap styles

I'm currently working with Twitter Bootstrap's CSS, but it seems to be overriding some of my custom classes. Initially, I placed it before my own CSS in the HTML header (I am using jade and stylus template engines): doctype html html head ...

Guide on how to navigate to a different page upon logging in with react-router-dom V5

I have implemented routing in my create-react-app using react-router-dom version 5.2.0. My goal is to use react-router for redirects and route protection within the application. The initial landing page is located at /, which includes the login/signup fun ...

Issue with Rails application using Bootstrap 5 vertical tabs - tab panel not populating after clicking beyond the first element

Hello, I am a beginner in the world of Ruby on Rails and I am encountering an issue with populating my tab panel with information from the database. While the tabs are displayed correctly, clicking on them only shows the information from the first tab (u ...

How can we store image file paths in MongoDB?

I'm currently working on developing a REST API using nodeJS, express, mongoose, and mongodb. I have successfully implemented file uploads with multer and saved the files to a folder. Now, I need to save the path of the uploaded file to a mongodb docum ...

The onClick function was not recognized as a valid function when it was called

I encountered an error when passing an onClick function as a prop in my React app from one component to another. The error message displayed is Uncaught TypeError: handleOnClick is not a function. Here is the function I am passing: propList = ['a&apos ...

Tips for Enhancing JavaScript Performance

Is there a way to enhance my JavaScript code like this: $(window).scroll(function() { if ($('#sec1').isVisible()) { $('.js-nav a.m1').addClass('active'); } else { $('.js-nav a.m1').removeClas ...