Bootstrap Collapse - open the given id fragment

Pierre de LESPINAY picture Pierre de LESPINAY · Nov 16, 2012 · Viewed 23.6k times · Source

Imagine a Bootstrap collapse with 3 parts

<div class="panel-group" id="accordion">
    ...
    <div id="accordionOne" class="panel-heading"></div>
    ...
    <div id="accordionTwo" class="panel-heading"></div>
    ...
    <div id="accordionThree" class="panel-heading"></div>
</div>

Is there a simple way to make the plugin open the given HTTP fragment identifier ?

Example http://myproject/url#accordionTwo would open the second accordion

Answer

fxbt picture fxbt · Nov 16, 2012
$("#accordionTwo").collapse('show');

To open the given HTTP fragment identifier, try this:

$(document).ready(function() {
    var anchor = window.location.hash;
    $(".collapse").collapse('hide');
    $(anchor).collapse('show');
});

EDIT:

As pointed by bart in the comments: be careful with targeting .collapse because this class is also used for the navigation bar when the viewport is xs.