All submenus will be shown simultaneously

All sub menus are displayed at once when any button that triggers the event is clicked.

For a live demonstration, click here:

https://jsfiddle.net/saidmontiel/734szqLg/9/

I'm interested in having only one submenu appear at a time.

I am aware that there are plenty of resources available to fix this issue with just copying and pasting code snippets. However, I prefer to learn the solution myself. So, a big thanks in advance to those who will assist me in my learning process.

// Mobile Navigation Scripts   
    var menuButton = $('.menu-toggle');
    var navul = $('.nav-container');
    var siteContent = $('#content');
    $('.menu-item-has-children').prepend('<button class="sub-menu-btn" aria-controls="submenu" aria-expanded="false"><img width="10px" height="10px" src="http://cdn.mysitemyway.com/icons-watermarks/flat-square-white-on-black/classic-arrows/classic-arrows_double-chevron-down/classic-arrows_double-chevron-down_flat-square-white-on-black_512x512.png"></button>');    
    
    menuButton.click(function () {
        if ($(this).attr("aria-expanded") === "false") {
            navul.toggleClass("menu-opened");
            siteContent.addClass('offCanvas').removeClass('onCanvas');
            $(this).attr("aria-expanded", "true");
        } else {
            navul.removeClass("menu-opened");
            siteContent.addClass('onCanvas').removeClass('offCanvas');
            $(this).attr("aria-expanded", "false");
        }
    });
    
    var subMenuBtn = $('.sub-menu-btn');
    var subMenu = $('.sub-menu');
    var hasChildren = $('menu-item-has-children');
    
    subMenuBtn.click(function () {
        if ($(this).attr("aria-expanded") === "false") {
            subMenu.closest('ul').slideToggle().toggleClass('submenu-opened');
            $(this).attr("aria-expanded", "true");
            
        } else {
            subMenu.slideToggle().removeClass('submenu-opened');
            $(this).attr("aria-expanded", "false");
        }
    });
body {
  background-image: url('https://image.freepik.com/free-vector/modern-abstract-background_1048-1003.jpg');
  background-repeat:repeat;
}
    .menu-toggle {
      display: block;
      background-size: 30px 50px;
      background-repeat: no-repeat;
      background-position: 97%;
      background-color: #000;
      height: 50px;
      width: 100%;
      border: 0;
      border-radius: 0;
      box-shadow: initial;
      text-shadow: initial; }
      ...
...
                 </li>
                <li>
          ...
</ul></div>

Answer №1

Click on the button to expand or collapse the menus accordingly

 subMenuBtn.click(function () {
        var parentElement = $(this).parent()
        if ($(this).attr("aria-expanded") === "false") {
           parentElement.find('> ul').slideToggle().toggleClass('submenu-opened');//expand the selected menu
           parentElement.siblings().find('ul').slideUp().removeClass('submenu-opened'); //collapse all other menus at the same level
            $(this).attr("aria-expanded", "true");

        } else {
            parentElement.find('> ul').slideToggle().removeClass('submenu-opened');
            parentElement.siblings().find('ul').slideUp().removeClass('submenu-opened');
            $(this).attr("aria-expanded", "false");
        }
    });

See it in action here: https://jsfiddle.net/uwn9ehmz/1/

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

Utilizing jquery.load to fill out a form following unsuccessful validation with ajax in CodeIgniter

After exploring numerous form validation tutorials that utilize jQuery Ajax, I have observed a common trend - they all focus on successful form validation. However, my quest is to uncover the process of displaying errors when server-side validation fails. ...

Error occurs when attempting to change the color of a dynamically generated div, resulting in the message: "Type Error: Unable to assign a value to the property '

I'm facing an issue with my code where I have a parent div that loads with a random color, and upon clicking a button, it should create a new colored div inside. However, I keep encountering the following error: TypeError: Cannot set property ' ...

Achieve seamless alignment of radio group labels alongside radio buttons through the use of only CSS

After using a table to display radio buttons with labels in the past, I am now attempting to achieve the same result using only CSS. Is there a CSS technique that will allow me to position the label text neatly on top of the corresponding radio button? He ...

Exploring the contrast between RFC and RFCE in the realm of ReactJS

As a newcomer to Reactjs, I'm curious about the distinction between "react functional component" and "react functional component export". Can someone help explain? Below is an example of a react functional component: import React from 'react&apo ...

Tips for transitioning this JavaScript code into jQuery syntax

Below is my JavaScript code: javascript: function executeCode() { var d = document; try { if (!d.body) throw (0); window.location = 'http://www.example.com/code?u=' + encodeURIComponent(d.location.href); } catch (e) { ...

Error encountered during Angular unit testing: Unable to read the 'id' property of a null value. (Jasmine, Karma)

I am currently working on writing unit tests for a specific component in my Angular application. The component uses a currentUser variable both in the component logic and the HTML template. I have hardcoded this variable by mocking it in every test using c ...

Modify the class and color of a Font Awesome icon when clicked

My goal is to change the class and color of an icon when it is clicked. Here is the code I am using: $(".sim-row-edit-icon").click(function(){ alert("Icon clicked"); // on click please change icon and color to red }); <link href="https://stackpath. ...

Having trouble navigating menus and submenus?

Customizing CSS Styles On my website, I have two different classes: menu and leftside. Both classes include the ul and li elements. However, when I try to use ul and li in the left side as well, they end up matching with the styles of the menu ul and li. ...

How can you leverage jQuery to append a new parameter to the existing URL without causing a page refresh?

One of our clients is facing a challenge with their staff page on the website. When a visitor clicks on a staff member's name, jQuery is used to fade out the current bio and fade in the selected bio on the right side. Although this functionality work ...

What is preventing me from successfully sending data to a .json file using Ajax?

I'm trying to create a basic server that can send data to a .json file and then retrieve that data from another page. However, I am facing an issue with storing the data in the .json file. I attempted to use the code below, but it was unsuccessful: ...

What is the best way to initiate a JavaScript AJAX call within a PHP function?

My PHP if statement currently just reloads the page: header('Location: index.php'); Check out the site here Instead, I am looking to use a basic AJAX request in JavaScript to load a page called register-success.php into the div: function load ...

After the geolocation is retrieved, employing a callback function

I have been developing a web service program that tracks the location of users using geolocation. The program initiates geolocation to locate the user and then proceeds to record the location. However, since geolocation relies on a callback function to ret ...

Is it possible to maintain line breaks when using ".text" or ".textContent"? Any other options or solutions available? Workarounds to consider?

When trying to copy HTML from one element and paste it as text in another element, I noticed that newlines are not retained in the latest versions of Firefox and Chromium. For instance, if you run the code below (with valid HTML), the output will have the ...

increase the number of rows in the table automatically

I've encountered an issue while working on a form that involves getting a value from a jQuery spinner and dynamically adding that number of rows to a table inside the form. Despite using firebug to debug, I couldn't pinpoint the exact cause of th ...

Searching JSON Data for Specific String Value Using JavaScript

I am looking for a straightforward approach to search my JSON string using JavaScript. Below is the PHP code that generates my JSON String: <?php $allnames = array(); $res = mysql_query("SELECT first,last FROM `tbl_names`"); while ($row = mysql_fetch_ ...

Styling code for a layout with two columns aligned to the left using

I am looking to create a layout where two pieces of text are displayed side by side in columns using CSS. The left-hand column will have variable length text, while the right-hand column will have fixed length text. The desired layout should show the two ...

Adjust the positioning of the background and create a smooth fade effect for

Is there a way to simultaneously change the background position and display an image in front of it? My current solution involves using a second div with padding to center it, but when I hover over the padding of the first div, the image does not change. ...

Managing Import Structure in Turborepo/Typescript Package

I am currently working on creating a range of TypeScript packages as part of a Turborepo project. Here is an example of how the import structure for these packages looks like: import { Test } from "package-name" import { Test } from "package ...

Rely on the razor method for generating URLs

I need to direct to a specific page, so I have implemented a JavaScript function in my MVC project: function rootUrl(url) { var _rootUrl = '@Url.Content("~")'; var x = url; if (url. ...

Error in ASP.NET/C# - utilizing Ajax to pass selected value from a dropdown menu

I've been working on linking two drop down lists using JQuery AJAX, but so far I haven't had any success. Here's my ASP.NET code for the drop downs: <td><a href="#" title="Choose the park that you would like. Mandatory Field."> ...