skip to Main Content

I would like to programmatically collapse all but the first item in a Bootstrap 3 collapsible accordion. However, I’m running into some weird behaviour. Please check out this fiddle and let me know what’s wrong.

http://jsfiddle.net/k9o2j53a/

$('button').click(function(){
    var panels = $('#accordion').find('.panel-collapse');
    panels.collapse('hide');
    panels.first().collapse('show');
});

When the button is clicked for the first time the behaviour is different than when it is clicked the second time. Subsequent clicks seem to alternate between the desired behaviour and collapsing of every item.

3

Answers


  1. Chosen as BEST ANSWER

    I found the solution I was looking for. It turns out that collapsible elements must first be initialized, otherwise the first call to show/hide will perform the initialization itself and cause this 'toggle' behaviour which I've been observing and trying to avoid.

    So, to show/hide a panel, it's best to write:

    $('#accordion').find('.panel-collapse').collapse({toggle: false}).collapse('show');
    

    Then to hide all but the first:

    $('#accordion').find('.panel-collapse:gt(0)').collapse({toggle: false}).collapse('hide');
    $('#accordion').find('.panel-collapse:first').collapse({toggle: false}).collapse('show');
    

  2. Try this:

    $('#a').click(function(){
       var panels = $('#accordion').find('.panel-collapse').not("#collapseOne");
       panels.collapse('hide');
       panels.collapse('show');
    });
    

    Updated fiddle

    If I understood your question correctly. You want to “collapse all but the first”. Pretty straightforward to just use .not("selector") to exlude it.

    Login or Signup to reply.
  3. delay the show so that the hide animation is complete:

     $('#a').click(function(){
        $('#accordion .in').collapse('hide');
    
      setTimeout(function(){ $('#collapseOne').collapse('show'); }, 500);
    
     });
    

    http://jsfiddle.net/k9o2j53a/6/

    you can adjust the delay to suit your purposes

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search