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.
$('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
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:
Then to hide all but the first:
Try this:
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.delay the show so that the hide animation is complete:
http://jsfiddle.net/k9o2j53a/6/
you can adjust the delay to suit your purposes