Pierre de LESPINAY
Pierre de LESPINAY

Reputation: 46198

Bootstrap Collapse - open the given id fragment

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

Upvotes: 20

Views: 25317

Answers (4)

fxbt
fxbt

Reputation: 2596

$("#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.

Upvotes: 36

Brezelfelder
Brezelfelder

Reputation: 61

Yet another solution, a bit smaller and compact:

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

Upvotes: 5

neillh
neillh

Reputation: 104

This line will open the correct hash

location.hash && $(location.hash + '.collapse').collapse('show');

Upvotes: 8

Kelvin
Kelvin

Reputation: 5317

For really simple and quick to implement hash routing, you could try something like Routie

routie({
    accordionOne: function() {
        $('#accordionOne').collapse('show');
    },
    accordionTwo: function() {
        $('#accordionTwo').collapse('show');
    },
    accordionThree: function() {
        $('#accordionThree').collapse('show');
    }
});

Upvotes: 2

Related Questions