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.

    var panels = $('#accordion').find('.panel-collapse');

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.



  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:

       var panels = $('#accordion').find('.panel-collapse').not("#collapseOne");

    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:

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

    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