20

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

Pierre de LESPINAY
  • 40,390
  • 50
  • 195
  • 282

4 Answers4

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

Community
  • 1
  • 1
fxbt
  • 2,236
  • 14
  • 17
  • 1
    Thank you, I know that I can open it with javascript and even without (using the class `in`). The question is about controlling the opened part from the HTTP fragment identifier. – Pierre de LESPINAY Nov 16 '12 at 08:26
  • 1
    I edited my answer. You can improve this by deleting the `.replace("#", "")` part and just selecting the element to show with `$(anchor)` – fxbt Nov 16 '12 at 08:35
  • 1
    Be careful with targeting `.collapse` because this class is also used for the navigation bar when the viewport is `xs`. – bart Jul 29 '15 at 19:13
8

This line will open the correct hash

location.hash && $(location.hash + '.collapse').collapse('show');
neillh
  • 104
  • 2
5

Yet another solution, a bit smaller and compact:

$(document).ready(function() {
  var anchor = window.location.hash;
  $(anchor).collapse('toggle');
});
Rustam A. Gasanov
  • 13,604
  • 8
  • 54
  • 72
Brezelfelder
  • 61
  • 1
  • 3
2

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');
    }
});
Kelvin
  • 4,909
  • 21
  • 35
  • There is the [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange) event, but it's not supported by every browser. If you want to do this without adding another dependency, have a look at http://stackoverflow.com/questions/2161906/handle-url-anchor-change-event-in-js – Kelvin Nov 16 '12 at 08:53