Bootstrap: Collapse other sections when one is expanded

If you don't want to change your markup, this function does the trick:

jQuery('button').click( function(e) {
    jQuery('.collapse').collapse('hide');
});

Whenever a BUTTON is clicked, all sections become collapsed. Then bootstrap opens the one you selected.


Using data-parent, first solution is to stick to the example selector architecture

<div id="myGroup">
    <button class="btn dropdown" data-toggle="collapse" data-target="#keys" data-parent="#myGroup"><i class="icon-chevron-right"></i> Keys  <span class="badge badge-info pull-right">X</span></button>
    <button class="btn dropdown" data-toggle="collapse" data-target="#attrs" data-parent="#myGroup"><i class="icon-chevron-right"></i> Attributes</button>
    <button class="btn dropdown" data-toggle="collapse" data-target="#edit" data-parent="#myGroup"><i class="icon-chevron-right"></i> Edit Details</button>

    <div class="accordion-group">
        <div class="collapse indent" id="keys">
            keys
        </div>

        <div class="collapse indent" id="attrs">
            attrs
        </div>

        <div class="collapse" id="edit">
            edit
        </div>
    </div>
</div>

Demo (jsfiddle)

Second solution is to bind on the events and hide the other collapsible elements yourself.

var $myGroup = $('#myGroup');
$myGroup.on('show.bs.collapse','.collapse', function() {
    $myGroup.find('.collapse.in').collapse('hide');
});

Demo (jsfiddle)

PS: the strange effect in the demos is caused by the min-height set for the example, just ignore that.


Edit: changed the JS event from show to show.bs.collapse as specified in Bootstrap documentation.


If you are using Bootstrap 4, and you don't want to change your markup:

var $myGroup = $('#myGroup');
$myGroup.on('show.bs.collapse','.collapse', function() {
$myGroup.find('.collapse.show').collapse('hide');
});

For Bootstrap v5

Add the data-bs-parent attribute to the collapse elements. Thanks to @Diana for the update.

For Bootstrap v4.1

Add the data-parent attribute to the collapse elements instead on the button.

<div id="myGroup">
    <button class="btn dropdown" data-toggle="collapse" data-target="#keys"><i class="icon-chevron-right"></i> Keys  <span class="badge badge-info pull-right">X</span></button>
    <button class="btn dropdown" data-toggle="collapse" data-target="#attrs"><i class="icon-chevron-right"></i> Attributes</button>
    <button class="btn dropdown" data-toggle="collapse" data-target="#edit"><i class="icon-chevron-right"></i> Edit Details</button>

    <div class="accordion-group">
        <div class="collapse indent" id="keys"  data-parent="#myGroup">
            keys
        </div>

        <div class="collapse indent" id="attrs"  data-parent="#myGroup">
            attrs
        </div>

        <div class="collapse" id="edit"  data-parent="#myGroup">
            edit
        </div>
    </div>
</div>