IrfanClemson
IrfanClemson

Reputation: 1779

JQuery to Simulate Accordion in a Loop

I am trying to implement a solution loosely based on: How can I expand and collapse a <div> using javascript?

But my code is different. In a loop I have the following:

var results_div_id = "results_tab_div" + i;
var results_html = "<strong>Tract: " + results.features[i].attributes.TRACT + "</strong> <br />";
results_html += "Owner: " + results.features[i].attributes.OWNER + "<br />";
$("#" + results_div_id).html(results_html);
$("#" + results_div_id).addClass("results_div");

As you can see, I am creating a new dynamic div and then populating that with the results_html variable and then applying a 'results_div' class to make rounded edges etc. What I need to do is that users could click on the the 'Tract' word or some image next to it to expand the rest of the div. So, by default, all content within the div except the line with 'Tract' should be invisible.

I tried to apply display:none but that hides the entire div--as it should. Any way around it? Here is the CSS

div .results_div{
  display:none;    
}

I have tried to make the line with the 'Tract' as separate div with a new class and then tried to force it to be visible but doesn't work--nothing still shows from the results_html content.

BTW, a bunch of these dynamically created loops are then added, one below another, in a jquery tabbed interface...

Thanks!

Upvotes: 0

Views: 1260

Answers (1)

JSess
JSess

Reputation: 648

From my understanding, you want to loop through a dataset and generate accordions based upon them.

If that's the case, something like this may help - http://jsfiddle.net/jmsessink/c4035syu/

Here's my loop to create the accordion inner content -

for (x = 0, y = results.features.length; x < y; x++) {
       resultsStr +=
           '<div class="accordion-item">' +
               '<h3>Tract: ' + results.features[x].attributes.TRACT + '</h3>' +
               '<div class="accordion-content">' +
                   '<p>Owner: ' + results.features[x].attributes.OWNER + '</p>' +
               '</div>' +
           '</div>';
}

Basically, I've made an object based upon your example data, looping through it, generating a string which includes the elements for the accordion structure, and finally inserting the string as HTML into the accordion container that exists in the DOM already. Then, you can basically either take any accordion plugin that you prefer and initialize it, or like what I did (if it's as simple as the example from the link you've provided) just make your own.

Hopefully this is a step in the right direction for you.

Upvotes: 1

Related Questions