DrDefenestrator
DrDefenestrator

Reputation: 21

Accordion Open/Close All In Section

I have several basic-accordion-container 's. When I run this, it will expand ONE group of accordions (which it should) but I can not go and expand another group of accordions until I close the opened group.

basicAccordianToggle = function(){
if ($('.expand-all-these').length) {
  $('.expand-all-these').on('click', function(e){
    e.preventDefault();
    if ($('.expand-all-these').hasClass('collapsed')) {
      $(this).parents('.basic-accordion-container').find('.collapse').collapse('hide');
      $(this).parents('.basic-accordion-container').find('.expand-all-these').html('Expand All <span class="plus">+</span>');
      $(this).parents('.basic-accordion-container').find('.expand-all-these').removeClass('collapsed');
    }else{
      $(this).parents('.basic-accordion-container').find('.collapse').collapse('show');
      $(this).parents('.basic-accordion-container').find('.expand-all-these').html('Collapse All <span class="plus">-</span>');
      $(this).parents('.basic-accordion-container').find('.expand-all-these').addClass('collapsed');
    }
  })
}

}

Upvotes: 1

Views: 177

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115222

You have to check hasClass for the clicked element instead of all elements, so use this to refer clicked element.

basicAccordianToggle = function(){
if ($('.expand-all-these').length) {
  $('.expand-all-these').on('click', function(e){
    e.preventDefault();
    if ($(this).hasClass('collapsed')) {
    // ---^^^^-------- here
      $(this).parents('.basic-accordion-container').find('.collapse').collapse('hide');
      $(this).parents('.basic-accordion-container').find('.expand-all-these').html('Expand All <span class="plus">+</span>');
      $(this).parents('.basic-accordion-container').find('.expand-all-these').removeClass('collapsed');
    }else{
      $(this).parents('.basic-accordion-container').find('.collapse').collapse('show');
      $(this).parents('.basic-accordion-container').find('.expand-all-these').html('Collapse All <span class="plus">-</span>');
      $(this).parents('.basic-accordion-container').find('.expand-all-these').addClass('collapsed');
    }
  })
}
}

Upvotes: 1

Related Questions