How do I keep the current tab active with twitter bootstrap after a page reload?
You'll have to use localStorage or cookies to manage that. Here's a quick and dirty solution that can be vastly improved, but may give you a starting point:
$(function() {
// for bootstrap 3 use 'shown.bs.tab', for bootstrap 2 use 'shown' in the next line
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
// save the latest tab; use cookies if you like 'em better:
localStorage.setItem('lastTab', $(this).attr('href'));
});
// go to the latest tab, if it exists:
var lastTab = localStorage.getItem('lastTab');
if (lastTab) {
$('[href="' + lastTab + '"]').tab('show');
}
});
Got this to work using cookies and also removing the 'active' class from any other tabs and tab panes... and adding the 'active' class to the current tab and tab pane.
I'm sure there's a better way to do this, but this appears to work in this case.
Requires the jQuery cookie plugin.
$(function() {
$('a[data-toggle="tab"]').on('shown', function(e){
//save the latest tab using a cookie:
$.cookie('last_tab', $(e.target).attr('href'));
});
//activate latest tab, if it exists:
var lastTab = $.cookie('last_tab');
if (lastTab) {
$('ul.nav-tabs').children().removeClass('active');
$('a[href='+ lastTab +']').parents('li:first').addClass('active');
$('div.tab-content').children().removeClass('active');
$(lastTab).addClass('active');
}
});
All other answers are correct. This answer will take into account the fact that one might have multiple ul.nav.nav-pills
or ul.nav.nav-tabs
on the same page. In this case, the previous answers will fail.
Still using localStorage
but with a stringified JSON
as the value. Here is the code:
$(function() {
var json, tabsState;
$('a[data-toggle="pill"], a[data-toggle="tab"]').on('shown', function(e) {
var href, json, parentId, tabsState;
tabsState = localStorage.getItem("tabs-state");
json = JSON.parse(tabsState || "{}");
parentId = $(e.target).parents("ul.nav.nav-pills, ul.nav.nav-tabs").attr("id");
href = $(e.target).attr('href');
json[parentId] = href;
return localStorage.setItem("tabs-state", JSON.stringify(json));
});
tabsState = localStorage.getItem("tabs-state");
json = JSON.parse(tabsState || "{}");
$.each(json, function(containerId, href) {
return $("#" + containerId + " a[href=" + href + "]").tab('show');
});
$("ul.nav.nav-pills, ul.nav.nav-tabs").each(function() {
var $this = $(this);
if (!json[$this.attr("id")]) {
return $this.find("a[data-toggle=tab]:first, a[data-toggle=pill]:first").tab("show");
}
});
});
This bit can be used on the entire app over all pages and will work for both tabs and pills. Also, make sure the tabs or pills are not active by default, otherwise you will see a flicker effect at page load.
Important: Make sure the parent ul
has an id. Thanks Alain