Retain Twitter Bootstrap Collapse state on Page refresh/Navigation
Solution 1
You can very easily solve this by a cookie. There is a lot of simplified libraries, like https://github.com/carhartl/jquery-cookie as I use in the example below :
<script src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
add the following code to a script section (#accordion2
refers to the modfied twitter bootstrap example, I list afterwards)
$(document).ready(function() {
var last=$.cookie('activeAccordionGroup');
if (last!=null) {
//remove default collapse settings
$("#accordion2 .collapse").removeClass('in');
//show the last visible group
$("#"+last).collapse("show");
}
});
//when a group is shown, save it as the active accordion group
$("#accordion2").bind('shown', function() {
var active=$("#accordion2 .in").attr('id');
$.cookie('activeAccordionGroup', active)
});
And you are done! Here a modified version of the example at http://twitter.github.com/bootstrap/javascript.html#collapse with clickable links, when you go back - the last shown accordion group opens up automatically
<div class="accordion" id="accordion2">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseOne">
Collapsible Group Item #1
</a>
</div>
<div id="collapseOne" class="accordion-body collapse in">
<div class="accordion-inner">
Link : <a href="http://google.com">google.com</a>
</div>
</div>
</div>
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo">
Collapsible Group Item #2
</a>
</div>
<div id="collapseTwo" class="accordion-body collapse">
<div class="accordion-inner">
Link : <a href="http://stackoverflow.com">stackoverflow.com</a>
</div>
</div>
</div>
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseThree">
Collapsible Group Item #3
</a>
</div>
<div id="collapseThree" class="accordion-body collapse">
<div class="accordion-inner">
Link : <a href="http://cryptozoologynews.blogspot.com/">cryptozoology news</a>
</div>
</div>
</div>
</div>
Solution 2
In Bootstrap 3.x.x you have to use the following script to save the last open state in cookies.
HTML Markup
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">Collapsible Group
Item #1 </a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse in">
<div class="panel-body">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson
ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food
truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put
a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim
keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus
labore sustainable VHS.
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">Collapsible Group
Item #2 </a>
</h4>
</div>
<div id="collapseTwo" class="panel-collapse collapse">
<div class="panel-body">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson
ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food
truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put
a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim
keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus
labore sustainable VHS.
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapseThree">Collapsible
Group Item #3 </a>
</h4>
</div>
<div id="collapseThree" class="panel-collapse collapse">
<div class="panel-body">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson
ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food
truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put
a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim
keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus
labore sustainable VHS.
</div>
</div>
</div>
</div>
Jquery
$(document).ready(function () {
//when a group is shown, save it as the active accordion group
$("#accordion").on('shown.bs.collapse', function () {
var active = $("#accordion .in").attr('id');
$.cookie('activeAccordionGroup', active);
// alert(active);
});
$("#accordion").on('hidden.bs.collapse', function () {
$.removeCookie('activeAccordionGroup');
});
var last = $.cookie('activeAccordionGroup');
if (last != null) {
//remove default collapse settings
$("#accordion .panel-collapse").removeClass('in');
//show the account_last visible group
$("#" + last).addClass("in");
}
});
Solution 3
I tried the technique suggested above and it worked for me (sort of) but calling .collapse("show") seemed to break the accordion toggle behavior in some instances. Opening first panel would leave previously opened panel in open state. I got round this with jQuery by adding class "in" instead:
$(document).ready(function() {
var last=$.cookie('activeAccordionGroup');
if (last!=null) {
//remove default collapse settings
$("#accordion .panel-collapse").removeClass('in');
//show the account_last visible group
$("#" + last).addClass("in");
}
});
Otherwise, thanks davidkonrad putting me on right track.
Solution 4
Another option available is to use the url hash.
$(document).ready(function () {
var hash = window.location.hash;
if (hash) {
$("#accordion .panel-collapse").removeClass('in');
$(hash).addClass('in');
}
$('#accordion').on('shown.bs.collapse', function () {
var activeId = $("#accordion .in").attr('id');
window.location.hash = activeId;
});
$('#accordion').on('hidden.bs.collapse', function () {
window.location.hash = '';
});
});
Solution 5
Thanks for this, it works. I modified it a bit to simply retain the show/hide state of a specific DIV (and not specific to showing only one DIV in a list of DIVs).
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<script language="javascript" type="text/javascript">
function retainDivCollapsedState(nameOfDiv, nameOfHeader) {
// when the div is shown, save a cookie with a value of 'true'
$("#" + nameOfDiv).on('shown.bs.collapse', function () {
$.cookie(nameOfDiv, "true"); // this is a cookie. named the same as the control (poor practice) for brevity
});
// when the div is collapsed, remove the same cookie
$("#" + nameOfDiv).on('hidden.bs.collapse', function () {
$.removeCookie(nameOfDiv);
});
// on page load, show or hide the div (and stylized the header) according to the cookie (if it exists)
var showDiv = $.cookie(nameOfDiv);
if (showDiv != null) {
$("#" + nameOfDiv).addClass("in"); // The div to show
$("#" + nameOfHeader).removeClass("collapsed"); // The header to stylize as expanded
}
};
</script>
<script language="javascript" type="text/javascript">
$(document).ready(
retainDivCollapsedState("divName", "divHeaderName")
);
</script>
Related videos on Youtube
gnudle
Updated on July 09, 2022Comments
-
gnudle almost 2 years
I'm using Bootstrap "collapse" plugin to make an accordion for a long list of links. The accordion-body tag includes "collapse" so all the groups are collapsed when the page loads. When you open a group and click on a link, it takes you to a new page to see some detail and then you click a back link or the browser back to return to the list. Unfortunately, when you return the accordion is back in its collapsed state and you have to open the group again and find where you were. I anticipate a lot of this back and forth navigation and this behavior is going to be frustrating.
Is there some way to preserve the user's place and go back to it, or just prevent the page from reloading or the javascript from firing again.
I thought the solution might be along these lines, but not sure. Twitter bootstrap: adding a class to the open accordion title
-
Sherbrow over 11 yearsHave you looked into using the hash to refer the opened accordion ?
-
gnudle over 11 yearsHere's a related item regarding using cookie to remember earlier state of the accordion: stackoverflow.com/questions/1458724/…
-
Ravimallya over 9 yearsUpdate: This question was for Bootstrap 2.x.x, for Bootstrap 3.x.x refer my answer.
-
-
gnudle over 11 yearsThanks, I haven't tried it yet, but with your explanation and hearing the same advice from a friend I think this is the way to go.
-
davidkonrad over 11 yearsthe items must have an id, i forget to mention that
-
user1337 over 8 yearsThink you could post a jsfiddle page or similar? I think yours does what I want it to do, but I'm missing something.
-
Matt about 8 yearsThis was a great answer and helped me a lot but I think you need to point out that you had to download a special add-on for jquery to get the cookie part to work. I see the selected answer mentions this but I kind of got tunnel-vision when I saw your answer related directly to Bootstrap 3.x
-
MatsLindh almost 8 yearsBootstrap 3 updates the event name to
shown.bs.collapse
(as shown in answer below) -
davidkonrad almost 8 years@MatsLindh, you are correct - this was a BS 2.x issue, two years after tagged with bootstrap-3 and the specific 3.x answer.
-
mesosteros almost 8 yearsOr just use localStorage instead of $.cookie.
-
javapatriot almost 7 yearsHave you experienced an issue with the first accordian not staying open when going to an interior page?
-
mharr almost 6 yearsTo update this answer for Bootstrap 4, replace the references to ".in" class to ".show" class. Including changing .removeClass and .addClass to ("show").
-
Plonetheus about 2 yearsJust a note for anyone looking here, some of your html isn't updated to the newest version of Bootstrap. For example, it would be
data-bs-toggle
instead ofdata-toggle