"Using jQuery to toggle the visibility of multiple divs individually when

I am facing an issue with dynamically generated divs in asp.net. My goal is to display the contents of each div by clicking on its header. I attempted to achieve this using the following code:

 $(function () {
            var myHead = $(".toggle-container").find(".toggle-header");
            var myBody = $(myHead).parent().find(".toggle-content");
            $(myHead).click(function () {
                if ($(myBody).css('display') === 'none') {
                    $(this).children('i').removeClass('icon-chevron-sign-down').addClass('icon-chevron-sign-up');
                    $(this).parent().find(".toggle-content").slideDown("slow");
                } else if ($(myBody).css('display') === 'block') {
                    $(this).children('i').removeClass('icon-chevron-sign-up').addClass('icon-chevron-sign-down');
                    $(this).parent().find(".toggle-content").slideUp("slow");

                };
            });
        });

However, this solution only works for the first header and does not collapse the children content for the rest of the headers. You can view my current progress on this JsFiddle. Any suggestions on how to fix this issue would be greatly appreciated.

Answer №1

The issue stemmed from how the content was being shown or hidden. The solution lies in locating the relevant content for the clicked header. Instead of using the code

var myBody = $(myHead).parent().find(".toggle-content");
, it should be placed inside the click handler as var myBody = $(this).next()

 $(function () {
     var myHead = $(".toggle-container .toggle-header");
     $(myHead).click(function () {
         var myBody = $(this).next()
         if ($(myBody).css('display') === 'none') {
             $(this).children('i').removeClass('icon-chevron-sign-down').addClass('icon-chevron-sign-up');
             $(this).parent().find(".toggle-content").slideDown("slow");
         } else if ($(myBody).css('display') === 'block') {
             $(this).children('i').removeClass('icon-chevron-sign-up').addClass('icon-chevron-sign-down');
             $(this).parent().find(".toggle-content").slideUp("slow");

         };
     });
 });

Demo: Fiddle

Please note that the up-down arrows are still not functioning correctly due to the need to use find() instead of children()

A simpler version could be:

jQuery(function ($) {
    var $heads = $(".toggle-container .toggle-header");
    $heads.click(function () {
        var $this = $(this);
        $this.find('i').toggleClass('icon-chevron-sign-down icon-chevron-sign-up');
        $this.next().slideToggle("slow");
    });
});

Demo: Fiddle

Answer №2

Here is a more efficient solution:

Your original code had assigned the variable myBody a value at load time, causing it to only target the first element of its kind.

I have now updated the code so that the value setting for the myBody variable occurs within the click event using $(this). This ensures that the correct element is always found relative to the clicked element.

 $(function () {
     var myHead = $(".toggle-container").find(".toggle-header");
     $(myHead).click(function () {
         var myBody = $(this).parent().find(".toggle-content");         
         if ($(myBody).css('display') === 'none') {
             $(this).children('i').removeClass('icon-chevron-sign-down').addClass('icon-chevron-sign-up');
             $(this).parent().find(".toggle-content").slideDown("slow");
         } else if ($(myBody).css('display') === 'block') {
             $(this).children('i').removeClass('icon-chevron-sign-up').addClass('icon-chevron-sign-down');
             $(this).parent().find(".toggle-content").slideUp("slow");

         };
     });
 });

Check out the Demo

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

Respond to onClientClick based on the button choice made by the user

In my code, there is an OnClientClick event set up like this: OnClientClick="return getErrors();". This function contains the following body: function getErrors() { var errorString = "some errors"; return $('<div id="dialog-message" title= ...

Is there a way to toggle or collapse a table row with a unique identifier using Angular and Bootstrap?

Currently handling Angular and Bootstrap in my work, but facing challenges with table manipulation and collapsing rows. I fetch data from a database and showcase it in a dynamically generated table using *ngFor and two rows within an ng-container. My goal ...

What causes ngDoCheck to be triggered upon setTimeout resolution?

I'm pondering why ngDoCheck gets triggered when setTimeout finishes. Here is a simple component setup I have: @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css ...

Ajax UpdateProgress not functional

How can I resolve the issue where my AJAX UpdateProgress bar in ASP.NET is not running when executing a query in the correct format upon button click? Any solutions or help would be greatly appreciated. <html xmlns="http://www.w3.org/1999/xhtml"> ...

The multilanguage feature in ProcessWire seems to be experiencing some issues and

Hello everyone, I'm a beginner with processwire (https://processwire.com) and I'm attempting to set up Multi Language for my website. Despite following all the help and tutorials available, I still can't seem to get it working. Let me outli ...

Is there a way to determine if two distinct selectors are targeting the same element on a webpage?

Consider the webpage shown below <div id="something"> <div id="selected"> </div> </div> Within playwright, I am using two selectors as follows.. selectorA = "#something >> div >> nth=1&q ...

Jest test failing due to issues with a stateful React component containing an asynchronous function

I'm currently going through a Jest testing tutorial on Pluralsight that can be found here. Even though I have written the code exactly like the author, my test is not passing for some reason. Link to my Pull request on the author's repo: https:/ ...

Add more functionality to the server.js script

I have the server.js file, which serves as the entry point for my Node application and is responsible for invoking three different functions (these functions are only called once when the server is up, such as creating child processes, validation, etc), wh ...

Creating dynamic autocomplete suggestions using Jquery and Ajax

I've been attempting to utilize Jquery's Autocomplete feature found here http://jqueryui.com/autocomplete/#default Despite my efforts, the output is not functioning properly. To troubleshoot, I've created a FIDDLE which you can access by c ...

ThreeJs interactive grid

Looking to create a rectangular "support" grid that allows users to hover over and place objects on specific tiles. For example, hovering over (x:0 y:15) and clicking will result in an object being placed at (x:0 y:15). https://i.sstatic.net/X0Rnu.png Th ...

Send documents via a form by utilizing the text input function

At the moment, I am currently utilizing type="file" for file uploads. However, my specific scenario requires me to upload directly from a text box with the complete file path provided. <form action="upload_file.php" method="post" enctype="multipart/for ...

"Use jQuery to change the value on click to 22

I am facing an issue with my code that is supposed to change the anchor and id values when clicked. Although the value and anchor do change, it only works once. Can anyone help me understand why it's not working? HTML <a href="#" id="enable-edit-b ...

The slideshow feature on W3 Schools does not start automatically when the page loads

After following the W3Schools tutorial to create a slideshow, I found that the animations are working correctly. However, only three dots appear on the screen and I have to manually click on one of them to view the pictures. var slideIndex = 0; sh ...

What is the way to check for a condition within jQuery?

Is there a way to dynamically add a class to an "a" tag upon clicking it, and then alert if the nearest div with the class "jitender" is present? <head>     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />     <ti ...

What can I do to keep the divs in position when resizing the screen?

I've noticed that the list items are shifting out of place when I resize the screen. I want them to stay in their original position no matter the screen size. I suspect it has something to do with the .fixedwidth class, but I've been struggling t ...

JavaScript is throwing an error when clicking on functions and managing the z-index property

I am experiencing difficulties with my website code. I have defined all the necessary functions and CSS, but I keep encountering errors such as "clicked is not defined," even though it is clearly present in the script. The goal of the code is to bring the ...

Utilizing JQuery's .Toggle function in conjunction with a stylish CSS transform button

I am trying to create a toggle menu that shows and hides itself without requiring the button to be clicked twice. I have added e.preventDefault(); which solves the issue, but now the button does not transform as intended. $(document).ready(function() { ...

What is the best way to trim text to fit within a predetermined block size automatically?

I have a block with width specified in percentage and height in rem. I need to populate it with text of random lengths. The number of visible lines should be an integer, and the last line must end with a link saying "...read full text". This functionality ...

Retrieve a DOCX file via AJAX response

I am encountering an issue with a Django function that returns a file: ... return FileResponse(open('demo.docx', 'rb')) I am using ajax to fetch it on the client side. Now, I need to download it on the client side. This is the code I a ...

What are some solutions to correct a tab layout that is utilizing absolute positioning?

Although I understand how absolute positioning works, it is currently disrupting the layout in this particular case. Using min-height with media queries for various screen sizes seems like a viable solution, but it's not foolproof considering that the ...