jQuery Animated List - Nested items are unresponsive to clicks

Looking to create a dynamic nested list using jQuery for animations, but unsure of the best approach.

Currently, I'm adjusting the length of the parent list item and revealing the nested items.

The issue is that the parent item's length covers the nested items. I want to click on a nested item (like Edit Profile, Add Music, Playlists, etc) to trigger a different action. Right now, I'm just testing with alert prompts.

HTML

<div id="sidebar-menu" class="col-md-12">
  <ul>
    <li class="sidebar-menu-item" data-length="2"><span id="IWantToClickHere">Profile</span>
      <ul class="blue-special sublist">
        <li>Edit Profile</li>
        <li>Other</li>
      </ul>
    </li>
    <li class="sidebar-menu-item" data-length="2">Library [<span class="purple-special">3537</span>]
      <ul class="blue-special sublist">
        <li>Add Music</li>
        <li>Playlists</li>
      </ul>
    </li>
    <li class="sidebar-menu-item" data-length="0">Friends</li>
    <li class="sidebar-menu-item" data-length="0">Stations</li>
    <li></li>
    <li class="sidebar-menu-item" data-length="0">Settings</li>
    <li class="sidebar-menu-item" data-length="0">Logout</li>
  </ul>
</div>

JS

$(document).ready(function() {
  $('.sidebar-menu-item').click(function() {
    //When: Menu is opened, 
    if ($(this).hasClass('opened-menu-item')) {
      $(this).removeClass('opened-menu-item');
      //Reset Menu-Item to default height of 20px per menu-item
      $(this).animate({
          height: "20px"
        },
        1000,

        //Hide nested content
        function() {
          $(this).find('.sublist').css('display', 'none');
        });
    } else {
      //When: Menu is closed
      $(this).addClass('opened-menu-item');
      $(this).find('.sublist').css('display', 'inherit');
      //Set Menu-Item length to be the number of nested li * 35
      var animateHeight = Number($(this).data("length")) * 35;
      if (animateHeight != 0) {
        $(this).animate({
            height: animateHeight + "px"
          },
          1000);
      }
    }
  });
});

Try out the jsfiddle here: http://jsfiddle.net/W4Km8/8065/

Answer №1

Utilize event.stopPropagation()

http://jsfiddle.net/W4Km8/8066/

$('.blue-special.sublist').click(function(e){
    alert('click');
    e.stopPropagation();
  })

By using this code, you can prevent the click event from propagating to the parent elements. This is important for maintaining the functionality of your page when dealing with nested elements.

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 properly modifying an attribute within an array of objects in JavaScript using ReactJS

My array of objects looks like this: this.state = { itemSquare: [{ item: "bomb", status: false }, { item: "bomb", status: false }, { item: "bomb", status: false }, { item: "bomb", status: ...

Optimizing Image Size According to the Container, Not the Screen Size: A Guide

After exploring various resources on responsive images, I have come across a challenge that has me stumped. It seems like it should be simple, but I can't quite figure it out: How can I serve the appropriate image size based on container width rather ...

How to modify the link to ensure that a particular tab is already selected when the page loads

How to Add Script for Linking to Rawdata Tab I need help loading specific page content with the Rawdata tab open instead of the Summary tab. What code should I add to the link to ensure that the page loads with "Rawdata"? https://i.stack.imgur.com/avETs. ...

Ways to trigger Bootstrap modal through a PHP GET call

I have been searching for a solution to create a modal similar to this one, but I haven't found anything yet. My requirement is that when we pass true in a GET request, the modal should be displayed. Otherwise, if there is no value specified in the $ ...

my divs are not being affected by the max-width property and are retaining their

I've been learning CSS and HTML through an interesting tutorial on Udacity. Here's the code I've been working on: .image{ max-width: 50%; } .app{ display: flex; } .description{ color: red; max-width: 705px; } <h1 class="title" ...

The Feedback Form jQuery is not providing any data

I'm facing an issue with my html page that includes an ajax query to a php file. The purpose of this php file is to send a message and then return a response to the ajax query. However, no matter what I try, I am unable to receive any response from th ...

Is it possible to target elements based on a specific CSS3 property they use?

Is there a method to target all elements in the DOM with a border-radius other than 0? If anyone has suggestions, it would be greatly appreciated! ...

The Jquery .submit() method seems to be malfunctioning following the execution of the .ajax() function

JQuery .submit() function is experiencing issues after the .ajax() function has run. CODE: if ($("#NetBanxFormTag").attr("action") != "") { AddOdemeLog($("#<%=TxtCC.ClientID %>").val(),MusteriAdSoyad,$("#<%=HFDrm.ClientID %>").val(), $ ...

What is the best way to determine the quantity of identical items in the django templating language?

My goal is to create a table that organizes items by type, all retrieved from my database. Currently, I can display the items and their corresponding types without any issues in a table format. However, I want to avoid repeating the same type multiple time ...

Creating a SAS URL for Azure Blob storage in Node.js using the generateBlobSASQueryParameters method from the @azure/storage-blob module

Hello, I am working with an Azure storage account where I upload and create a SAS URL to download images. Below is the code snippet that I have used: const { BlobServiceClient, StorageSharedKeyCredential, BlobSASPermissions, generateBlobSASQueryPar ...

Create containers on the right side using HTML

Struggling to align the small boxes on the right side while keeping the left boxes from blending under them? I've attempted various solutions, but each time it seems like the code breaks. By the way, I utilized a generator to create the grid. Here is ...

Waiting for content to load in Angular's UI-Router

Working with UI-Router in Angular 1.7, I am facing an issue wherein I want to change the state and wait for the content to load before scrolling to the bottom of the page. // Using a class method onCreate() { this.post().then(response => { ...

Error with JSON data from the Twitch TV API

I am having trouble with the Twitch API. When a streamer is live, I work with the "Stream" property, but if they are not streaming, I need to refer to another link. I use the getJSON function to fetch the necessary API link and work with it. However, my lo ...

I'm experiencing difficulties in installing dependencies for my project through npm, as it keeps showing an error

Recently, I decided to delve into the world of HTML5 and javascript games by running a browser game from Github. The game that caught my eye is called BrowserQuest, and you can find it on Github. A hiccup arose while using npm debug: 237 error 404 Not ...

What is the best way to handle multiple axios calls with pagination in a React application?

Discussing React Pagination and Handling Multiple Axios Calls In my current project, I am faced with the challenge of mapping through an array of numbers and making sequential API calls for each one. The API I'm working with returns paginated results ...

Error callback not being invoked on save() method in AngularJS service

So I am currently using the AngularJS Restful Service $resource in my project. However, when I try to call the $save function and provide an error callback, it does not get invoked. Surprisingly, even though the server sends a 418 error, which is not a suc ...

Waiting to run a function until a specified function has finished its execution

I have a piece of code that needs to address synchronization issues related to the execution order of MathJax functions. Specifically, I need to ensure that all the MathJax operations are completed before running the setConsoleWidth() function. What is t ...

Discovering the art of incorporating various color palettes within a single stylesheet using HTML

I'm curious about incorporating multiple color schemes into a single stylesheet that can be activated by clicking, similar to the functionality found in platforms like WordPress and Magento. These platforms offer themes with various color options avai ...

Is it possible to implement smooth scrolling in HTML without using anchor animation?

Is it feasible to implement a more seamless scrolling experience for a website? I'm referring to the smooth scrolling effect seen in MS Word 2013, but I haven't come across any other instances of this. I've heard that AJAX can make such th ...

Guide to setting a default child route in react-router and updating the URL as needed

Currently, I am utilizing react-router v3 and have a segment of my routing code as follows: ... <Route path='dashboard' component={Dashboard}> <Route path='overview' component={Overview}/> <Route path='scan&apo ...