What is the best way to expand the subcategories within a list?

I have successfully implemented a script to open my hamburger menu. However, I am facing an issue with subitems as some list items contain them. How can I modify the script to ensure that the subitems expand when clicked instead of just hovering?

function myResponsive() {
var x = document.getElementById("myMenu");
if (x.className === "menu-hori") {
x.className += " responsive";
} else {
x.className = "menu-hori";
}
}
.menu-hori{
width: 1100px;
margin: auto;
height: auto;
margin-top: 15px;
padding: 0px;
display: table;
z-index: 100;
background: grey;
}

.menu-hori ul {
    margin: 0;
    padding: 0;
    list-style: none;
}

.menu-hori ul ul {
    opacity: 0;
position: absolute;
top: 160%;
visibility: hidden;
transition: all .4s ease;
-webkit-transition: all .4s ease;
}

.menu-hori ul ul ul {
top: 0%;
left: 160%;
}

.menu-hori ul ul li:hover > ul {
    top: 0%;
    left: 100%;
    opacity: 1;
    visibility: visible;
}

.menu-hori ul li:hover > ul {
    opacity: 1;
    top: 100%;
    visibility: visible;
}

.menu-hori ul li {
    float: left;
    position: relative;
}


.menu-hori ul ul li { float: none; }

.menu-hori ul li {
background-color: grey;
cursor: pointer;
}

.menu-hori ul a {
text-decoration: none;
display: block;
color: white;
padding: 10px 15px;
width: auto;
min-width: 100px;
text-align: center;
text-shadow: 0px -1px 0px rgba(0,0,0,.2);
}

.menu-hori ul li:hover { background-color: #069CDE; }

.menu-hori ul li a:hover { background-color: #069CDE; }

.menu-hori span.dropBottom,span.dropRight {
  display: block;
  box-shadow: inset 2px 0px 0px #069CDE;
  position: absolute;
  left: 0px;
  width: 100%;
  height: 100%;
  top: 0px;
}

.menu-hori span.dropBottom {
  box-shadow: inset 0px 2px 0px #069CDE;
  position: absolute;
  width: 100%;
  bottom: 0px;
} 

.menu-hori a:hover {
  background-color: #ddd;
  color: black;
}

.menu-hori .icon {
  display: none;
}

@media screen and (max-width: 1100px) {
  .menu-hori{
width: 100%;
min-height: 40px;
height: auto;
margin-top: 15px;
padding: 0px;
display: table;
z-index: 100;
background: grey;
display: block;
  }
}

@media screen and (max-width: 1100px) {
.menu-hori ul li{
float: none;
}

.menu-hori ul li a{
display: none;
}

.menu-hori ul li a.icon{
display: block;
text-align: right;
}

.responsive ul li a{
display: block;
}
}
<div class="menu-hori" id="myMenu">
  <ul>
  <li><a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myResponsive()">☰</a></li>
     <li><a>BEVEILIGINGSCAMERA</a><span class="dropBottom"></span>
     <ul>
       <li><a href="#" class="dropRight">Analoog</a>          
         <ul>
           <li><a href="#">irc10</a></li>    
           <li><a href="#">ird29</a></li>    
           <li><a href="#">ird1</a></li>  
         </ul>
       </li>
   </ul>
     </li>
</div>

I have provided the code snippet for better context. It seems like a lot now, but I need to refine my JavaScript so that clicking on list items will also expand the sub items instead of just hovering over them as it currently does.

Answer №1

Here is a demonstration of a simple two-step menu using jQuery.

 $('#cssmenu li.active').addClass('open').children('ul').show();
    $('#cssmenu li.has-sub>a').on('click', function(){
      $(this).removeAttr('href');
      var element = $(this).parent('li');
      if (element.hasClass('open')) {
        element.removeClass('open');
        element.find('li').removeClass('open');
        element.find('ul').slideUp(200);
      } else {
        element.addClass('open');
        element.children('ul').slideDown(200);
        element.siblings('li').children('ul').slideUp(200);
        element.siblings('li').removeClass('open');
        element.siblings('li').find('li').removeClass('open');
        element.siblings('li').find('ul').slideUp(200);
      }
    });

HTML:

<div id="cssmenu">
<ul>
   <li><a href="#">Home</a></li>
   <li class="active has-sub open"><a href="#">Products</a>
      <ul>
         <li class="has-sub"><a href="#">Product 1</a>
            <ul>
               <li><a href="#">Sub Product</a></li>
               <li><a href="#">Sub Product</a></li>
            </ul>
         </li>
         <li class="has-sub"><a href="#">Product 2</a>
            <ul>
               <li><a href="#">Sub Product</a></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>

Check out the code demo on CodePen

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

Using Jquery's $.each() method within an ajax call can be a powerful

Is it possible for a jQuery each loop to wait for Ajax success before continuing when sending SMS to recipients from an object? I want my script to effectively send one SMS, display a success message on the DOM, and then proceed with the next recipient. O ...

Ways to change object to string in javascript

My object has the following structure: Object {Dry Aged Ribeye(medium): "1" , Dry Aged Ribeye(rare): "1" , Dry Aged Ribeye(well): "1" , favorite_tables: "{"dc76e9f0c0006e8f919e0c515c66dbba3982f785":[]}" } I am trying to insert this into My ...

Combining two divs to share the same linear gradient and shadow effect

Greetings to all our valued partners! I am seeking guidance on how to achieve the following task for a web application I am developing: Within my webapp, I have designed a stylish NavBar similar to the examples depicted in the images (in AdobeXD it is di ...

Modifying JavaScript Code in Inspect Element Editor

When I modify the HTML content using Chrome's Inspect Element editor, any changes made are immediately visible. However, when I make changes to the JavaScript code, the modifications do not take effect. For example, if I have a button that triggers a ...

Unsupported MIME format

I'm encountering an issue where my stylesheet is not applying to my handlebars. It was working fine yesterday, but today I'm seeing a MIME error and I'm unsure of the reason behind it. Any assistance would be greatly appreciated. Server Cod ...

Is it possible to establish a default route in Next.js?

Is it possible to set up default routes in Next.js so that all routes, or a specific list of routes, will automatically navigate to a designated page? My project involves using Next.js to create the marketing website, as well as the sign-up and sign-in pr ...

Deleting the v-stepper-header number with Vuetify

I have been searching everywhere in an attempt to resolve this issue, but I have not been able to find a solution. Is there a way to remove the numbers from the v-stepper-header? - Using Vuetify version: 1.5.6 Current: https://i.stack.imgur.com/gLxFX.png ...

Steps to show a message on screen for a duration of 3 seconds using JavaScript

setTimeout(function(){ document.getElementById("alarmmsg").innerHTML=msg; },3000); The code above is successfully displaying the message but it's not going off the screen as expected. What might be causing this issue? ...

Encountering a problem with AJAX displaying error code 80020101 while attempting to retrieve a string from a

I encountered an error while running my code: Microsoft JScript runtime error: Could not complete the operation due to error 80020101. I came across this thread on Stackoverflow that talks about a similar issue: Ajax request problem: error 80020101 var d ...

Tips for changing the value of a TextField in React Material

I am faced with a challenge regarding a form that is populated with data from a specific country. This data is fetched from a GraphQL API using Apollo Client. By default, the data in the form is read-only. To make changes, the user needs to click on the e ...

Checking the image loading functionality with Cypress

I am interested in testing Cypress to verify that an image is successfully loaded onto a page. Here is a snippet of my source code: import React from "react"; export default class Product extends React.Component { render() { return ( <div ...

Generate a JSON object based on the request.body information

Currently using NodeJs along with Express for building a REST API. The functionality is all set up and running smoothly, but I'm facing an issue in comprehending how to iterate through the request.body object and validate its fields for any undefined ...

Variations between <div/> and <div></div>

When using Ajax to load two divs, I discovered an interesting difference in the way they are written. If I write them like this: <div id="informCandidacyId"/> <div id="idDivFiles"/> Although both divs are being loaded, only one view is added ...

The error notification is not appearing in the correct location

I've been troubleshooting my jQuery error function for hours now (including the success function). I'm struggling to figure out how to display an error message only below the button that I click. To help clarify my issue, I've created a JSFi ...

Performing multiple Axios POST requests within a loop in a REACT application with dynamic variables

For my form inputs, I have an array of labels named changing_variable, which depend on the user's selection from a dropdown menu and vary in value. I'm trying to pass this dynamic variable to Axios.post method to correctly input data into my dat ...

Unique text: "Enhancing User Interaction: Using a custom directive to dynamically evaluate

Introduction: A simple demonstration of HTML structure: <td ng-repeat="col in cols"> <div ng-bind-html="col.safeHTML"></div> </td> JavaScript controller code snippet: $scope.cols = [ { field : 'logo&apos ...

Develop a website using HTML and CSS for the front-end design, complemented by Java for the

I find myself at a standstill with a project I want to tackle, but unfortunately, my knowledge of modern web development, particularly full stack, is minimal. As a result, I am completely clueless on how to proceed. Here is what I am familiar with and what ...

Using CSS and JavaScript to create a gradient-style opacity effect for smoothly fading out content

Is there a way to achieve a gradient fade effect on the opacity of an iframe and its content? To provide an illustration, think of the bottom of the notification centre in Mountain Lion or iOS. The concept involves having the content within an iframe grad ...

Content Security Policy directive violation: Chrome extension policy error occured due to refusal to execute inline event handler

I've been working on a chrome extension to perform a simple task, but I've hit a roadblock with one line of HTML code that's causing issues with setting the correct permissions. Despite my efforts, I'm stuck on what exactly needs to be ...

Troubleshooting checkbox change not being detected by Ajax in JavaScript

I have encountered a problem with my AJAX JavaScript code that checks whether a checkbox is selected or not. The issue arises when fetching data from MySQL - the code works correctly for the first row, but always sends checkboxstatus = 1 for the subsequent ...