alec alec - 3 months ago 7
jQuery Question

add class to accordion's div wrapper when all of the accordion's panes are collapsed (using Twitter Bootstrap)

I have an accordion effect implemented on my website using Twitter Bootstrap like so http://getbootstrap.com/javascript/#collapse-example-accordion.

Toggling the panels open and closed doesn't seem to add a class to any parent elements, only the .panel-headings and .panel-collapses...

I want it to add a class to the parent element (div.bs-example in the documentation's example) when all of the accordion's panels are closed/collapsed.

Does Bootstrap have an option for doing that?

If not, it seems like this would not be too hard to achieve...


  • on clicking/collapsing an open
    .panel-heading
    add
    class="all-closed"
    to the parent element

  • on clicking/opening an un-opened
    .panel-heading
    remove
    "all-closed"
    class (if it exists)



But maybe Bootstrap has an option for this? Or maybe someone has some jQuery example to get me going in the right direction?

Answer

I eventually got some janky code to almost work... and just now discovered that I needed to use the .on method to make it truly work.

My solution looked like this:

$('.panel-group').on('click', 'a[data-toggle="collapse"]:not(".collapsed")', function() {
  $('.panel-group').addClass('allPanesClosed');
});
$('.panel-group').on('click', 'a[data-toggle="collapse"].collapsed', function() {                     
  $('.panel-group').removeClass('allPanesClosed');
});
Comments