I am trying to keep selected tab active on refresh with Bootstrap 3. Tried and checked with some question already been asked here but none of work for me. Don't know where I am wrong. Here is my code
HTML
<!-- tabs link -->
<ul class="nav nav-tabs" id="rowTab">
<li class="active"><a href="#personal-info" data-toggle="tab">Personal Information</a></li>
<li><a href="#Employment-info" data-toggle="tab">Employment Information</a></li>
<li><a href="#career-path" data-toggle="tab">Career Path</a></li>
<li><a href="#warnings" data-toggle="tab">Warning</a></li>
</ul>
<!-- end: tabs link -->
<div class="tab-content">
<div class="tab-pane active" id="personal-info">
tab data here...
</div>
<div class="tab-pane" id="Employment-info">
tab data here...
</div>
<div class="tab-pane" id="career-path">
tab data here...
</div>
<div class="tab-pane" id="warnings">
tab data here...
</div>
</div>
Javascript:
// tab
$('#rowTab a:first').tab('show');
//for bootstrap 3 use 'shown.bs.tab' instead of '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('selectedTab', $(e.target).attr('id'));
});
//go to the latest tab, if it exists:
var selectedTab = localStorage.getItem('selectedTab');
if (selectedTab) {
$('#'+selectedTab).tab('show');
}
Xavi's code was allmost fully working. But when navigating to another page, submitting a form, then being redirected to the page with my tabs was not loading the saved tab at all.
localStorage to the rescue (slightly changed Nguyen's code):
I prefer storing the selected tab in the hashvalue of the window. This also enables sending links to colleagues, who than see "the same" page. The trick is to change the hash of the location when another tab is selected. If you already use # in your page, possibly the hash tag has to be split. In my app, I use ":" as hash value separator.
JavaScript, has to be embedded after the above in a
<script>...</script>
part.Woe, there's so many ways to do this. I came up with this, short and simple. Hope this help others.
I tried this and it works: ( Please replace this with the pill or tab you are using )
I hope it would help somebody.
Here is the result: https://jsfiddle.net/neilbannet/ego1ncr5/5/