I'm currently using tabs with Twitter Bootstrap and want to select the same tab after a user has posted data and the page reloads.
How is this done?
My current call to inti the tabs looks like this:
<script type="text/javascript">
$(document).ready(function() {
$('#profileTabs a:first').tab('show');
});
</script>
My tabs:
<ul id="profileTabs" class="nav nav-tabs">
<li class="active"><a href="#profile" data-toggle="tab">Profile</a></li>
<li><a href="#about" data-toggle="tab">About Me</a></li>
<li><a href="#match" data-toggle="tab">My Match</a></li>
</ul>
Answer: Use the HTML5 localStorage Object In Bootstrap, if you refresh the page the tab is reset to default setting. However, you can use the HTML5 localStorage object to save some parameter for the current tab locally in the browser and get it back to make the last active tab selected on page reload.
Just add the class to your html. This will make the first tab active by default.
$(window). load(function(){ $('#tabs-2'). trigger('click'); });
To change between tabs, click the tab you want to become active. You can also use any of the below shortcut keys when working with tabs in most programs. Ctrl + Tab = Switch between open tabs. Ctrl + Shift + Tab = Switch between open tabs in opposite direction.
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');
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With