Tips for ensuring only one submenu is open at a time

I have successfully created a responsive menu that is working well.

However, I am facing an issue. I want only one menu to be open at a time.

When a submenu is opened, the other menus should be hidden. How can I achieve this?

Below is my Script code

$('.moremain').click(function(){
    $(this).next('.hrmenu ul ul').slideToggle();
    $(this).toggleClass("active");
});

Check out My Menu

Answer №1

Check out this interactive demonstration.

$(document).ready(function(){

$('.hrmenu > ul').before("<span class='main'></span>");
$('.hrmenu ul ul').before("<span class='moremain'></span>");





$('.main').click(function(){

$('.hrmenu > ul').slideToggle();
});

$('.moremain').click(function(){


$(this).next('.hrmenu ul ul').slideToggle();
        $(this).parents('li').eq(0).siblings().each(function(){
        var _toggle = $(this).find('.moremain').eq(0);
            if(_toggle.hasClass("active")){
                 _toggle.removeClass("active");
                 $(this).find('ul').eq(0).slideToggle();
            }
       
        });
$(this).toggleClass("active");
});


$(window).resize(function(){

if(window.screen()> 1000)
{
$('.hrmenu ul').show();
}
});


});
*{margin:0px;padding:0px}
.hrmenu{max-width:1000px;margin:0px auto}
.hrmenu ul{background:#06C;}
.hrmenu ul:after{content:"";display:block;clear:both}
.hrmenu ul li{float:left;position:relative;list-style-type:none;margin:1px;}
.hrmenu ul li a{padding:5px;text-decoration:none;font-size:16px;font-family:arial;color:#fff;margin:1px;display:inline-block;  }
.hrmenu ul li a:hover{background:#39C}

.hrmenu ul li:hover > ul{display:block}
.hrmenu ul li ul{display:none;position:absolute;width:140px;left:0}
.hrmenu ul li ul li{width:100%;background:#069;}
.hrmenu ul li ul li ul{left:100%;top:0;width:200px;}
.hrmenu ul li ul li ul li{background:#336;}

.hrmenu ul li ul li ul li ul li{background:#366;}

.main{display:none;height:19px;background:#003   url(threelines.png) no-repeat;cursor:pointer;text-align:right; }
.moremain{height:19px;display:none;width:19px;background:green;cursor:pointer;position:relative;  text-align: center;
  display: none;color:#fff}
.moremain:after{content:' + '; font-size:18px;}
.active{background:orange;display:none;  text-align: center; }
.active:after{content:' - '; font-size:18px;color:#fff;}
@media screen and (max-width:1000px)
{
.moremain{ display: inline-block;}
.main{ display: block;}
.hrmenu ul{background:none}
.hrmenu ul li{float:none;  background: rgb(5, 27, 61);}
.hrmenu ul{display:none}
.hrmenu ul li:hover > ul{display:none}
.hrmenu ul li ul{width:98%}
.hrmenu ul li ul{position:relative}
.hrmenu ul li a{width:86%}
.hrmenu ul li{width:98%}
.hrmenu ul li ul li ul{width:100%}
.hrmenu ul li ul li ul{left:0}

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='hrmenu'>
<ul>
   <li><a href='#'>Home</a></li>
   <li><a href='#'>Products</a>
      <ul>
         <li><a href='#'>Product 1</a>
            <ul>
               <li><a href='#'>Sub Product</a></li>
               <li><a href='#'>Sub Product</a></li>
            </ul>
         </li>
         <li><a href='#'>Product 2</a>
            <ul>
               <li><a href='#'>Sub Product Sub</a>
               <ul>
                   <li><a href='#'>Sub Product</a></li>
                   <li><a href='#'>Sub Product</a></li>                    </ul>
               </li>
               <li><a href='#'>Sub Product</a></li>
            </ul>
         </li>
      </ul>
   </li>
   <li><a href='#'>About</a></li>
   <li><a href='#'>Contact</a></li>
</ul>
</div>

Explanation : To switch the visibility of each sibling li, toggle its first ul when its moremain toggle has an active class.

Answer №2

Here is the solution you've been seeking

$(".hr-nav-wrapper").hrNavMenu({ 
        speed:800, //time in milliseconds - 1000,2000
        menuType :"fromLeft", //options are fromLeft, fromTop
        desktopListWidth : "fluid", // choose between fluid or default
        openEvent : "click", //choose click or mouseover
        multiple  : false //choose true or false

    });

Get your hands on this Multilevel menu

Answer №3

To create a dropdown menu, you don't necessarily need to use JavaScript; CSS can do the job just fine.

/*rules for all li elements*/
li{
    position:relative;/*allow submenu to use the position of its parent as reference */
    display:inline-block;
    padding:5px;
}

/*rules for only submenu li elements*/

/*submenus are displayed only when its li parent is hovered*/
li > ul{
    display:none;
    position:absolute;
}
li:hover > ul{
    display:block;
}

/*submenus of submenus are displayed at the right of their parent and on the same abscissa*/
li li:hover > ul{
    left:100%;
    top:0;
}

*{margin:0px;padding:0px;color:#fff}
ul{ list-style-type:none;}
a{ white-space: nowrap;}

.hrmenu ul{background:#06C;}
.hrmenu ul ul {background:#aaf;}
.hrmenu ul ul ul {background:#06C;}
.hrmenu ul ul ul ul {background:#aaf;}

/*rules for all li elements*/
li{
    position:relative;/*allow submenu to use the position of its parent as reference */
    display:inline-block;
    padding:5px;
}

/*rules for only submenu li elements*/

/*submenus are displayed only when its li parent is hovered*/
li > ul{
    display:none;
    position:absolute;
}
li:hover > ul{
    display:block;
}

/*submenus of submenus are displayed at the right of their parent and on the same abscissa*/
li li:hover > ul{
    left:100%;
    top:0;
}
<div class='hrmenu'>
<ul>
   <li><a href='#'>Home</a></li>
   <li><a href='#'>Products</a>
      <ul>
         <li><a href='#'>Product 1</a>
            <ul>
               <li><a href='#'>Sub Product</a></li>
               <li><a href='#'>Sub Product</a></li>
            </ul>
         </li>
         <li><a href='#'>Product 2</a>
            <ul>
               <li><a href='#'>Sub Product Sub</a>
               <ul>
                   <li><a href='#'>Sub Product</a></li>
                   <li><a href='#'>Sub Product</a></li>                    </ul>
               </li>
               <li><a href='#'>Sub Product</a></li>
            </ul>
         </li>
      </ul>
   </li>
   <li><a href='#'>About</a></li>
   <li><a href='#'>Contact</a></li>
</ul>
</div>

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

Tips for showcasing HTML as code tailored to certain programming languages

While browsing the web, I stumbled upon a website that had SQL code displayed with specific classes and styles applied to it. For example, table names were colored blue when inspected. Here is a glimpse of what I encountered: https://i.sstatic.net/WAacj.p ...

Make a request to the local API in a React Native mobile app by sending a GET request

Currently, I am working on a mobile application using React Native and utilizing SQL Server and NodeJS. The API for this project is located in my localhost. Upon running the application on an emulator, I encountered an issue when attempting to make a reque ...

Every time a GET request is made to the same route in Express.js, it seems to be stuck in a

Currently, I am working on an express application that requires a landing page to be rendered for the '/' route. This landing page consists of a text box and a submit button. The desired functionality is such that when a user enters some text int ...

Is it possible to access JSON with a numeric key and receive undefined as a result?

I've been attempting to extract information from my JSON data, but I keep getting an undefined result. Here is a snippet of my JSON: { "1": "A", "2": "B", "3": "C", "4": "D", "5": "E", "6": "F", "key":"pair" } This i ...

Is there an issue with my Ajax request?

I've been troubleshooting an issue where my function consistently returns an error condition when trying to make a simple Ajax call to a local JSON file. I've ruled out the possibility that it's a file system call by uploading the file, but ...

Node 18 is having trouble locating NPM and is unable to locate the module './es6/validate-engines.js'

Previously, I attempted to install Node.js without any issues. However, this time around, I am encountering difficulties accessing the npm package. While I can successfully retrieve the version of Node.js after installation, attempting to check npm -v or w ...

Choose children input textboxes based on the parent class during the onFocus and onBlur events

How can I dynamically add and remove the "invalid-class" in my iti class div based on focus events in an input textbox, utilizing jQuery? <div class="form-group col-md-6"> <div class="d-flex position-relative"> & ...

Issue with displaying HTML escaped characters such as "&#39" results in showing a pound sign instead of a single quote

Whenever I store data in my Java code, I employ HtmlUtils.htmlEscape to ensure that HTML characters are escaped. However, when retrieving the data and trying to display it in an HTML format (using AngularJS 1.6), the escaped characters (&rsquo;, &am ...

Guide to decoding JSONP data sent from a remote server

Working on retrieving data using JSONP. After observing the returned data in Firebug, I can confirm that it is being returned correctly. However, I am facing a challenge in figuring out how to parse it. Is the data returning as a nested array? The callback ...

Facing issues with receiving API response through Postman encountering error { }

In my MongoDB database, I have created documents for Families, Users, and Devices (https://i.stack.imgur.com/oeDU0.png). My goal is to retrieve all devices associated with a specific family using the family's Id provided in the HTTP request. For examp ...

How can you create a blurred effect on a navbar?

Looking to achieve a unique blur effect in the background of my navbar component. The standard CSS blur effect isn't giving me the desired result, so I'm seeking some guidance on how to customize it. For example: https://i.sstatic.net/bPEXZ.png ...

Warning: Potential Infinite Loop when using Vue JS Category Filter

I developed a program that filters events based on their program and type. The program is working correctly, however, an error message stating "You may have an infinite update loop in a component render function" keeps popping up. I suspect that the issue ...

In PHP/HTML, input submit does not work with CSS styling

I am struggling with styling the input submit button in my form. I want the button to appear as text with a change in background and font color on hover. Any solutions? input[type="submit"] { font-family: made, mirage; text-decoration: none; backg ...

Is it possible to initiate validation on an HTML element without the presence of a form?

Is it possible to trigger validation on an HTML element without using a form? For example, I have set the required attribute on a field, but when I click the Save button, the field doesn't display the red outline indicating validation failure. I susp ...

Vue.js component communication issue causing rendering problems

When it comes to the Parent component, I have this snippet of code: <todo-item v-for="(todo, index) in todos" :key="todo.id" :todo="todo" :index="index"> </todo-item> This piece simply loops through the todos array, retrieves each todo obj ...

"An issue arises with jqPlot axes and legend when exporting images, as they are not rendering

After successfully rendering my jqPlot, I encountered an issue when exporting it as an image. The axes text and legend labels aren't displaying correctly in the exported image - the text seems to be shifting. Here's a comparison of the actual plo ...

How can I create a cube with complete beveling using Three.js?

I'm struggling to create a beveled cube in my project. I have come across the THREE.ExtrudeGeometry snippet in the documentation here. However, when I tried it out, I only managed to achieve beveled sides on the top and bottom faces like this: https: ...

Trouble with Map method not displaying data in Next.js

I am currently working on a Map Method but facing an issue. The data 1,2,3,4,5 is successfully displayed in the console.log, but not showing on the website. import React from 'react' export default function secretStashScreen() { const numbers = ...

Challenges with conditional statements in JavaScript

This is a simple code snippet for a ToDo-List application. The function InputCheck() is designed to validate if the input bar contains any value. If the input bar is empty, the function should not trigger the addTodo function. However, in its current stat ...

Utilizing Axios for Vue Multiselect on select/enter Event

I have successfully implemented a Vue Multiselect feature that retrieves options from my database using an axios call. This functionality works great as it allows users to select existing options or add new ones to create tags. While this setup is working ...