Dre
Dre

Reputation: 2172

Twitter Bootstrap collapse all but first

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.

Upvotes: 0

Views: 2114

Answers (3)

Cory
Cory

Reputation: 1283

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

Upvotes: 0

Dre
Dre

Reputation: 2172

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');

Upvotes: 0

brroshan
brroshan

Reputation: 1650

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.

Upvotes: 1

Related Questions