The slideUp/slideDown feature allows for the smooth sliding of all submenu elements

I am currently working on building a sidebar using HTML, CSS, and jQuery. One issue I am facing is with the slideUp/slideDown functionality not working correctly. Specifically, whenever I try to click on a submenu to close it, both open submenus disappear. Additionally, clicking on the submenus to open them is also not functioning as expected. I am puzzled about why this is happening and what mistake I might have made.

After attempting

console.log($(this).find('> .submenu'));
, I observed that the object has a length of 1. However, I am unsure as to why it is sliding all menus at once.

$(document).ready(function() {
  $('.has-submenu').click(function() {
    $(this).toggleClass('active');
    $(this).find('> .menu-item > .arrow').toggleClass('rotated');
    if ($(this).hasClass('active')) {
      $(this).find('> .submenu').slideDown("slow");
    } else {
      console.log($(this).find('> .submenu'));
      $(this).find('> .submenu').slideUp("slow");
    }
  });
});
@import url(https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,600);
@font-face {
  font-family: "ionicons";
  src: url("https://code.ionicframework.com/ionicons/2.0.1/fonts/ionicons.eot?v=2.0.1");
  // more CSS properties...
}

// more CSS code...

</script>
<div class="sidebar">
  <nav>
    <ul class="menu">
      <li class="has-submenu">
        <div class="menu-item">
          <span>Analytic plane geometry</span>
          <span class="arrow"></span>
        </div>
        <ul class="submenu">
          <li class="has-submenu">
            <div class="menu-item">
              <span>Line</span>
              <span class="arrow"></span>
            </div>
            <ul class="submenu">
              <li>1</li>
              <li>2</li>
            </ul>
          </li>
          <li class="has-submenu">
            <div class="menu-item">
              <span>Circle</span>
              <span class="arrow"></span>
            </div>
            <ul class="submenu">
              <li>1</li>
              <li>2</li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </nav>
</div>

If you want to view the demo, here is the link.

Answer №1

The problem arises due to the nesting of .has-submenu elements. This leads to event propagation up the DOM when clicking on a child element, causing all elements to toggle. To solve this issue, use stopPropagation() on the event passed to the handler:

$('.has-submenu').click(function(e) {
  e.stopPropagation();
  // add your remaining code here...
});

Moreover, it's advisable to cache your selectors to avoid recreating jQuery objects from this. Additionally, you can eliminate the need for an if condition by utilizing slideToggle(). Here is an updated approach:

jQuery(function($) {
  $('.has-submenu').click(function(e) {
    e.stopPropagation();

    var $el = $(this).toggleClass('active');
    $el.find('> .menu-item > .arrow').toggleClass('rotated');
    $el.find('> .submenu').slideToggle("slow");
  });
});
(CSS styles go here)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="sidebar">
  <nav>
    <ul class="menu">
      (Menu structure goes here)
    </ul>
  </nav>
</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 detecting when the MDC Snackbar has been closed using JavaScript

I'm currently working with Material Design's Snackbar in combination with VueJS. My goal is to detect when the snackbar has finished closing. The Snackbar object does have a property called isOpen, which allows me to check if the snackbar is ope ...

Prevent Node.js Express from automatically creating sessions

When I activate the session option in express using app.use(express.session({secret: "12345"}));, a session cookie is automatically created when the user visits a page for the first time. Is there a way to turn off this automatic behavior and have more co ...

Troubleshooting dropzone configuration issues and encountering the error message "Dropzone already attached"

I've been utilizing dropzone to manage image uploads on the front-end of my website. Initially, everything was running smoothly while using it as a CDN in the head section. However, I recently attempted to download and integrate it into assetic like t ...

"Passing an Empty String as Input in a NodeJS Application

app.post('/register',function(req,res){ var user=req.body.username; var pass=req.body.password; var foundUser = new Boolean(false); for(var i=0;i<values.length;i++){ //if((JSON.stringify(values[i].usernames).toLowerCase==JSON. ...

Transferring and bringing in components in React without ES6

I'm currently working on a react project and I want to export my ShoppingList class. However, I prefer not to use ES6 as I find it confusing. Here is the code for the ShoppingList class: class ShoppingList extends React.Component { render() { ...

What is the best way to delete a particular span element within an HTML table using JavaScript or JQuery?

Looking for assistance in removing a specific span element from the code snippet below, which was extracted from the elements tab of a browser. I am trying to delete the span located under the fourth 'td' within the 'tr' that has the cl ...

You are limited to storing only up to 2 items in the localStorage

My goal is to save items in local storage as an array of objects. Initially, it works perfectly and stores the first element in local storage as needed. However, I am facing an issue where I cannot store more than one element. Below is the code block that ...

Upon successful completion of the Ajax call, refresh the page without causing any blinking

Hey there, I'm facing an issue with my website, I've implemented ajax to fetch data from my API, and upon successful retrieval, I need to reload the page to display the information, However, sometimes the page blinks before reloading, while oth ...

Safari's problem with CSS transitions

This issue is specific to Safari, as it has been tested and works fine in Chrome, Opera, and Firefox. Upon hovering over a certain div (1), a child div (2) slides out by adjusting the left property. However, the child elements (buttons) within the second ...

The contents within the <div> element are not appearing on the webpage

I've been attempting to design a card that performs a 3D rotation when the mouse hovers over it. While I've successfully incorporated the background and front image of the card, I'm facing an issue with adding text to it. Here is the incorr ...

TR losing onclick action after second AJAX request

Seeking assistance with calling a PHP file that generates a table using JQuery. I am encountering issues with maintaining onclick functionality and highlighting in the TR after performing AJAX calls multiple times. Any guidance is appreciated. $.ajax({ ...

Guide to adding a new font to your Ember project

I am currently in the process of developing a website utilizing the MEEN Stack framework (Mongo, Ember, Express, Node). One challenge I am encountering is importing the Lato font family into my project to serve as the main font for the entire site. Despite ...

Including a hyperlink to a non-secure website from a secure relative path

Forgive me for asking what may be the silliest question ever, but I'm stumped: On my secure HTTPS page: <a href="../../../folder/index.php?openMenu=SEARCH">Advanced search</a> The link seems to work fine, but it points to an HTTP page i ...

Ways to enlarge image size without compromising the image resolution?

My image is in PNG format or as a blob. It has dimensions of 800px by 600px. However, when I try to resize it using various canvas methods like the one mentioned in this Stack Overflow thread: Resize image, need a good library, it loses quality. I wou ...

Guide to dynamically setting a value in an input field using JavaScript's document.querySelector

My goal is to input a value using Javascript. Check out my project link! Click on "add to cart" and then proceed to checkout to reach the checkout page. I am trying to automatically add a Zipcode value to the checkout page. I attempted this method but it ...

What is the Best Method for Filtering an HTML Table Efficiently?

Currently, I have an ajax function that calls a servlet to retrieve a list of products from multiple web services. This list can potentially contain up to 100,000 items and needs to be displayed in an HTML table. In order to provide users with a filtering ...

Tips on changing the included content of a personalized directive?

Currently utilizing angular 1.x and I've crafted a personalized directive named slider as displayed in the code below. I am attempting to integrate the content of the slider directive using transclude so that I can modify it within the transclude fun ...

Showing Real-Time Information in the Render Function

Looking for some guidance on how to create a dynamic Card using data from an API. I'm able to retrieve the data successfully, but I'm having trouble displaying it in the render method. Here's a snippet of my component where I use axios to f ...

Using Ajax.BeginForm with BeforeSend functionality

My MVC website has multiple Ajax.BeginForm elements, and I am looking to handle the beforeSend event of my Ajax calls. While the code below works for manual jquery ajax calls, it does not seem to work with the Ajax.BeginForm helpers: $.ajaxSetup({ &a ...

What's preventing me from changing module.exports? Why is my browser suddenly giving me errors after `npm run build` ran smoothly?

How come the browser is preventing me from executing the following code: Getters.js let Getters = {} Getters.foo = function(){ return 1; } Getters.bar = function(){ return 2; } module.exports = Getters; However, after running npm run build and serve -s ...