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
  • 44,700
  • 57
  • 210
  • 307

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,556
  • 19
  • 19
  • 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 Gasanov
  • 15,290
  • 8
  • 59
  • 72
Brezelfelder
  • 61
  • 1
  • 4
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
  • 5,227
  • 1
  • 23
  • 36
  • 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