Bootstrap Collapse - open the given id fragment
Asked Answered
C

4

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

Conclude answered 16/11, 2012 at 8:17 Comment(0)
B
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.

Bradstreet answered 16/11, 2012 at 8:20 Comment(3)
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.Conclude
I edited my answer. You can improve this by deleting the .replace("#", "") part and just selecting the element to show with $(anchor)Bradstreet
Be careful with targeting .collapse because this class is also used for the navigation bar when the viewport is xs.Blowing
B
8

This line will open the correct hash

location.hash && $(location.hash + '.collapse').collapse('show');
Broussard answered 13/1, 2013 at 23:58 Comment(0)
L
5

Yet another solution, a bit smaller and compact:

$(document).ready(function() {
  var anchor = window.location.hash;
  $(anchor).collapse('toggle');
});
Lutenist answered 14/1, 2015 at 10:56 Comment(0)
B
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');
    }
});
Broglie answered 16/11, 2012 at 8:39 Comment(1)
There is the onhashchange event, but it's not supported by every browser. If you want to do this without adding another dependency, have a look at #2162406Broglie

© 2022 - 2024 — McMap. All rights reserved.