Using Jquery to toggle the visibility of div elements with the same structure, but ensuring only one is

Many people have posed this question. I am attempting to create a functionality where a div can expand and collapse using a +/- button. I have 5 divs with class=="expanderContent". When the function below is triggered by a click, all 5 items expand or collapse at once.

Heading - Inner Inner Heading2 - Inner2 Inner2 Heading3 + .....

When I click the + next to Heading2, I only want Heading2 to expand or collapse, not all of them. The headings and content are inside the same div. Therefore, I need to identify which #expanderHead was clicked and only expand or collapse that specific sister .expanderContent, not all of them.

$(document).ready(function(){
      $("#expanderHead").click(function(){
        $(".expanderContent").slideToggle('2000', "linear", function () {
            // Animation complete.
        });
        if ($("#expanderSign").text() == "+"){
          $("#expanderSign").html("−")
        }
        else {
          $("#expanderSign").text("+")
        }
      });
    });

HTML (These are identical data, but won't be in production)

 // HTML code here... 

==== UPDATE ========

Probably not much help as it won't run in JSFiddle but does on my webserver.

https://jsfiddle.net/L98q71kg/

Answer №1

There are several issues with the current code. One major problem is the reuse of IDs, which should be switched to classes in order to use the same name.

The way hierarchy is being traversed in the code is incorrect. The siblings in the code are not the desired ones.

To fix these issues, follow these steps:

1) Change all IDs to classes

2) Implement the following JavaScript:

 $(document).ready(function(){
  $(".expanderHead").click(function(){
    $(this).closest('div').parent('.w-col.w-col-01.no_space_column').parent('.w-row.page_wide_row').children(".w-col-2").children('.expanderContent').slideToggle('1200', "linear", function () {
    });
    if ($(this).children(":first").text() == "+"){
      $(this).children(":first").html("−")
    }
    else {
      $(this).children(":first").text("+")
    }
  });
});

Answer №2

To achieve this, utilize the keyword 'this'. Here is an example of how it is done:

$(document).ready(function(){
  $("#expanderHead").click(function(){
    $(this).slideToggle('2000', "linear", function () {
        // Animation complete.
    });
    if ($(this).text() == "+"){
      $(this).html("−");
    }
    else {
      $(this).text("+");
    }
  });
});

jQuery automatically associates the scope of the callback with the element that triggered the click event, making this method effective.

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

I'm working on updating a field within a Firestore document using ReactJS

I am encountering an issue while attempting to update a field within a document in Firestore using ReactJS. Interestingly, others have successfully done it without any errors. app.js const app = initializeApp(firebaseConfig); const auth = getAuth(app); co ...

The persistent Bulma dropdown glitch that refuses to close

In the project I'm working on, I have implemented a Bulma dropdown. While the dropdown functions correctly, I am facing an issue when adding multiple dropdowns in different columns with backend integration. When one dropdown is open and another is cli ...

Maintaining consistent height using JavaScript

Dealing with equal height using just CSS can be a hassle, especially when you want to support older browsers like IE9. That's why I've decided to use JavaScript instead. If a user disables JavaScript, having unequal heights is the least of my con ...

Reverse lookup and deletion using Mongoose

Currently, I am attempting to perform a health check on the references within one of my collections. The goal is to verify if objects being referenced still exist, and if not, remove that particular _id from the array. Despite my efforts, I have not come ...

When text is added to div elements, they are mysteriously pushed downward. This strange phenomenon occurs with inline-block elements

Why does the first element get pushed down when its child contains text? What causes inline-block to behave this way? Is there a way to align divs side-by-side while still allowing them to have children? For example, I want the grey box to contain a list ...

Toggle the visibility of 2 Form Fields by checking the Checkbox

Hi, I am trying to display two form fields when a checkbox is selected. These fields are required, so they should only be displayed when the checkbox is checked and should be mandatory. However, I am facing issues with hiding the fields when the checkbox i ...

Transferring data from ng-init to <script> in AngularJS

Take a look at this code snippet: <div ng-init="companyData"> <script type="text/javascript"> window.timeline = new TL.Timeline('timeline-embed', sampleJson); </script> </div> Is there a method to include company ...

What advantages can be gained by opting for more precise module imports?

As an illustration, consider a scenario where I have an Angular 6 application and need to bring in MatIconModule from the @angular/material library. Two options could be: import { MatIconModule } from '@angular/material/icon'; Or import { Mat ...

Center an absolutely positioned div using CSS

What is the best way to position an absolute div at the center? <div class="photoFrame">minimum width of 600px, positioned absolutely</div> jQuery var screenWidth = $(window).width(); $('.photoFrame').css({'margin-left': ...

What is the method for specifying a string argument type from a string list and executing a mongo db query?

Is there a way to specify the argument type in a function as a string from a list of strings in order to run a MongoDB query? Here is what I am currently attempting: users.services.ts async findOne(key: "_id" | "email" | "username", value: string) { ...

How to eliminate spaces while preserving line breaks in a textarea using JS or jQuery

I have been trying to figure out how to remove extra spaces from the beginning and end of lines while keeping the line breaks intact. Here's what I attempted: function removeSpaces(string) { return string.split(' ').join(''); } ...

Repetitive process in JavaScript

I am struggling to write certain attributes to HTML using a recursive loop and I can't seem to get the code to work properly. The JSON data consists of an array of hashes with the following attributes: serno (serial number), parent_serno (serial numb ...

Problems arising from Jquery append functionality

When using the append method, my inner div is only attaching one WHEAT-COLORED-BOX, whereas when using appendTo, my inner div attaches all the required number of WHEAT-COLORED-BOXES. Therefore, in this case, appendTo gives the correct result while append f ...

Is there a way to ensure the collapsible item stays in its position?

I'm encountering an issue with the display of items within collapsible cards. Here is what it currently looks like: https://i.sstatic.net/DM8sX.png And this is how I want it to appear: https://i.sstatic.net/BXGpW.png Is there a way to achieve the ...

Is it necessary to have uniform spacing between links in a responsive navigation menu?

I am attempting to create a horizontal menu navigation system. I have multiple links in the navigation, and my goal is to evenly space them horizontally. Is there a way to achieve uniform spacing between links in a horizontal menu? HTML: <div id= ...

Determine if an object is empty in AngularJS

Is there a way to make a div element visible only after the user selects at least one checkbox? I attempted to achieve this using the following code within the div: <div class="col-md-1" ng-if="selectedElements.length > 0"> The variable selected ...

JavaScript multiplying an array in HTML

Snippet of HTML code <input name="productCode[]" value="" class="tInput" id="productCode" tabindex="1"/> </td> <input name="productDesc[]" value="" class="tInput" id="productDesc" readonly="readonly" /></td> <input name="pr ...

Develop a dynamic button using JavaScript to fetch information from an array

I'm struggling with incorporating this button creation code into my HTML using JavaScript. The code for creating the button element in JS file looks like this: var numery = ['A','B','C']; var numer = document.createE ...

Trouble with rendering inline images from markdown files in GatsbyJS

I've been trying to include inline images in my markdown file with the gatsby-remark-images plugin. However, I'm facing an issue where the image is not loading on my local host. I'm not sure if it's a syntax error or if I'm missing ...

Ways to prevent a centered list from shifting to the right

Although this question has appeared before, I am facing an issue with a list displayed as an inline block for use as a navigation bar. My goal is to center the nav bar on the webpage and ensure it scales down appropriately. <ul class="nav_bar"> ...