Tips for concealing all items except the currently selected branch when clicking on a menu drop-down

I am seeking a solution to open only one node at a time on click, and remove the 'is-active' class from other items.

Currently, there is excessive space taken up after opening multiple menu items. I want to ensure that only one node is open at a time by removing the 'is-active' class from the previous sub-item when switching to another sub-item.

The red square is used to open the item - could you assist me with this?

 const nav = document.querySelector('.menu-primary');

// const navElement = nav.querySelectorAll('.menu-item-has-children');

const navElementIcon = nav.querySelectorAll('.js-navigation-arrow');

// console.log(navElesment);

navElementIcon.forEach(function (element) {
    element.addEventListener("click", function() {
        let elementParent = element.closest('.menu-item-has-children');


        if (elementParent.classList.contains('is-active')) {
            elementParent.classList.remove('is-active');
        } else {
            elementParent.classList.add('is-active');
        }
    });
});
.menu-primary a {
  margin-right: 30px !important;
}
.menu-primary > li {
  position: relative;
  text-align: left;
}
.menu-primary > li:first-child .menu-item a {
  margin-top: 0;
}
.menu-primary > li:nth-child(4) {
  margin-top: 0;
}
.menu-primary > li > .menu-item-icon {
  top: 7px;
}
.menu-primary > li .sub-menu {
  position: static;
  transform: none;
  display: none;
  opacity: 1;
  visibility: visible;
}
.menu-primary > li .sub-menu > .sub-menu__list > li > .sub-menu__child-list {
  padding-left: 15px;
}
.menu-primary > li > a {
  display: inline-block;
  font-size: 16px;
  margin: 8px 0;
}
.menu-primary a {
  display: inline-block;
  font-size: 14px;
}

.menu-item-icon {
  display: flex;
  width: 15px;
  height: 15px;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 7px;
  right: 0;
  font-size: 8px;
  color: #fff;
  transform: rotate(180deg);
  transition: 0.2s;
  background: red;
  z-index: 10;
}
.menu-item.is-active > .sub-menu {
   display: block;
}

.menu-item {
  position: relative;
  margin: 5px 0;
}
.sub-menu__child-list {
    display: none;
    padding-left: 15px;
}
.menu-item.is-active > .sub-menu__child-list {
    display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="menu-primary">
// Menu items HTML code here
</ul>

Answer №1

Here are two different methods you can use, outlined in the code below. I trust this will be of assistance to you.

 const nav = document.querySelector('.menu-primary');

// const navElement = nav.querySelectorAll('.menu-item-has-children');

const navElementIcon = nav.querySelectorAll('.js-navigation-arrow');

// console.log(navElesment);

navElementIcon.forEach(function (element) {
    element.addEventListener("click", function() {
        let elementParent = element.closest('.menu-item-has-children');

        if (elementParent.classList.contains('is-active')) {
            elementParent.classList.remove('is-active');
        } else {
            /*
                If you just want to close active items in the same
                level that the one you're opening, use the command below.
                Example: If you click About Us -> Nasze gabinety ->
                Contact -> About Us, the Nasze gabinety is going to
                be opened yet.
            */
            // Array.from(elementParent.parentElement.children)
            //     .forEach((menuItem) => menuItem.classList.remove('is-active'));

            /*
                If you want to close all active items, use the command below.
                Example: If you click About Us -> Nasze gabinety ->
                Contact -> About Us, the Nasze gabinety is going to
                be closed.
            */
            Array.from(elementParent.parentElement.querySelectorAll('.is-active'))
                .forEach((menuItem) => menuItem.classList.remove('is-active'));

            elementParent.classList.add('is-active');
        }
    });
});
.menu-primary a {
  margin-right: 30px !important;
}
.menu-primary > li {
  position: relative;
  text-align: left;
}
.menu-primary > li:first-child .menu-item a {
  margin-top: 0;
}
.menu-primary > li:nth-child(4) {
  margin-top: 0;
}
.menu-primary > li > .menu-item-icon {
  top: 7px;
} 

... (Code continuation)

</ul>

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

Is it possible to activate ng-class following an ng-click event?

Here is the element in question: <a href="" ng-click="project.hasPhotos? removeFromProject(project, $index, currentPhoto) : addToProject($index, currentPhoto)" ng-class="{'selected-project': (belongsPhotoToProject(project, $index, currentPhot ...

The _doc property within Mongoose

I need assistance with this JavaScript code I have: app.post('/auth', async (req, res) => { try { const user = UserModel.findOne({email: req.body.email}).exec() if (!user) return res.status(404).json({ message: ...

Modifying the route category through parsing information from a JSON file

As a disclaimer, I must admit that I am venturing into unfamiliar territory here. Due to the ongoing restructuring at my workplace, I am required to take on additional tasks, such as creating visualizations. Here's the issue I'm facing: I have a ...

Having trouble with images not showing up properly when applying rounded CSS borders and opacity effects

Trying to solve a unique problem, I am seeking advice: On my website, I have included a 300 x 300 Pixel square png-image of a circle. Utilizing Zurb's Foundation 5.0.2 as a CSS Grid basis. My objective is to create a CSS-border around the circle and ...

Issue with retrieving date from MySQL column being a day behind in JavaScript (Node.js)

I currently have a Node.js server up and running as the API server for a service that I am developing for a company. The dates stored in the MySQL server that it connects to are related to event start times. Insertion of these dates is flawless, and when ...

Error TS2322: Type 'boolean' cannot be assigned to type 'undefined'. What is the best approach for dynamically assigning optional properties?

I am currently working on defining an interface named ParsedArguments to assign properties to an object, and here is what it looks like: import {Rules} from "../Rules/types/Rules"; export interface ParsedArguments { //other props //... ...

Implementing Ionic 4 with HTML2Canvas technology

Looking for a way to convert HTML into an image within an Ionic 4 application. I attempted to use html2canvas, however, it was unsuccessful and displayed the following message in the console: https://i.sstatic.net/4b4Sm.png Below is the code snippet I use ...

Error encountered: jQuery mobile version 1.3.0 - Unable to locate method 'refresh' for the table widget instance

I encountered an issue when using jQuery mobile 1.3.0 release: "Uncaught Error: no such method 'refresh' for table widget instance". However, the documentation suggests that it can be resolved by: Updating the labels in the cells. $(myTable).ta ...

Developing a synchronous loop in Node.js using the web-kit module

My goal with my app using node.js and webkit is to scan each proxy listed in a file.txt and determine if the proxy is working. However, I am encountering an issue where my loop does not wait for the "http.get" test on line 11 to complete before moving on ...

CSS-only checkboxes are not functioning properly in WordPress

I discovered some amazing pure CSS checkboxes that I wanted to implement (http://codepen.io/imohkay/pen/zFwec) on a WordPress website utilizing the Contact Form 7 plugin. However, after selecting these checkboxes, nothing seems to happen. To resolve this ...

Using div tags to organize content into rows

What is your interpretation of a row using div elements? Here is a simplified example in pseudocode: [DIV TAGS LEFT] [DIV TAGS CENTER] [DIV TAGS RIGHT] [INSERT CONTENT HERE] [DIV TAGS LEFT] [DIV TAGS CENTER] [DIV TAGS RIGHT] [INSERT CONTENT HERE] [ ...

Solution to trigger CSS :hover to refresh following a transition (such as expanding a menu)

While there are existing discussions on this topic, I am presenting my query for two specific reasons: It introduces a potential alternative solution The demo code could be helpful to individuals looking to emulate a menu Following a CSS transition, the ...

Jenkins process encounters issues with sed execution

I am currently facing an issue where a script that runs successfully locally encounters difficulties during our Jenkins build process, specifically with the 'sed' command. Below is the code snippet I am using. I have double-checked the file path ...

Creating unsightly class names using Node.js

Is it possible to automatically create random and unattractive class names? For example, is there a tool or plugin that can substitute the .top-header class with something like .a9ev within my CSS code? It would also be ideal if the class name in the HTML ...

Determine the point spread using Jquery

Trying to figure out the point spread and determine the winner of a game based on the entered scores. I've created a function to calculate the total number of points and another function to calculate the point spread and assign a winner label. However ...

Combine an array of objects using the main key in each object

I have an array of objects with different years and details var worksSummaryDetailsArr = [ { year: 2020, worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ] }, { year: 2021, worksSummaryDetailsObj: [ [Object], [Object], ...

The angularjs response data is mysteriously missing from the console display

I am struggling with the code below, as the data is not showing in the console log. I am new to Angular and would appreciate some help on how to display the data in HTML. this.$http.get(properties.client+'/123') .then(response => { ...

What is the best way to enable a child category on a treeview within a Vue component?

I am working with two vue components. The first component (parent component) looks like this: <template> ... <ul class="filter-category" v-for="list in categories"> <list-category :data="list" :category-id="category ...

Modifying the Inactive Tab Color in Material UI

For my application, I have a specific requirement where the active tab needs to be styled in red and the inactive tab in blue. Here is how the styling is set up: newStyle: { backgroundColor: 'red', '&$selected': { b ...

Tips for properly handling special characters in DOM elements

I'm encountering an issue while trying to set CSS based on a condition inside quotes. This is causing a syntax error for me. Can anyone provide assistance in finding a solution? <div> <span ng-class='{\' rdng-error-rate&bsol ...