How do you make Twitter Bootstrap Accordion keep one group open?

Here is an easy way to do it:

Bootstrap 4

$('.accordion .btn-link').on('click', function(e) { 
  if (!$(this).hasClass('collapsed')) { 
    e.stopPropagation(); 
  } 
});

from @mr_joncollette in the comments

Bootstrap 3

JsFiddle for Bootstrap 3.

Code for Bootstrap 3:

$('.panel-heading a').on('click',function(e){
    if($(this).parents('.panel').children('.panel-collapse').hasClass('in')){
        e.stopPropagation();
    }
    // You can also add preventDefault to remove the anchor behavior that makes
    // the page jump
    // e.preventDefault();
});

The code checks if the clicked element is the one that is currently shown (by the class “in”) and if it does have the “in” class, it stops the hiding process.


Deprecated Bootstrap 2

JsFiddle for Bootstrap 2.

Code for Bootstrap 2:

$('.accordion-toggle').on('click',function(e){
    if($(this).parents('.accordion-group').children('.accordion-body').hasClass('in')){
        e.stopPropagation();
    }
    // You can also add preventDefault to remove the anchor behavior that makes
    // the page jump
    // e.preventDefault();
});

Note: Be careful if you want to attach more click events on the accordion, since the e.stopPropagation() will block events that would occur after the check.

Leave a Comment