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');
}
This question is related to
jquery
twitter-bootstrap
tabs
twitter-bootstrap-3
Thanks for sharing.
By reading all the solutions. I came up with a solution that uses the url hash or localStorage depending on the availability of the latter with below code:
$(function(){
$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
localStorage.setItem('activeTab', $(e.target).attr('href'));
})
var hash = window.location.hash;
var activeTab = localStorage.getItem('activeTab');
if(hash){
$('#project-tabs a[href="' + hash + '"]').tab('show');
}else if (activeTab){
$('#project-tabs a[href="' + activeTab + '"]').tab('show');
}
});
For Bootstrap v4.3.1. Try below:
$(document).ready(function() {
var pathname = window.location.pathname; //get the path of current page
$('.navbar-nav > li > a[href="'+pathname+'"]').parent().addClass('active');
})
Well, this is already in 2018 but I think it is better late than never (like a title in a TV program), lol. Down here is the jQuery code that I create during my thesis.
<script type="text/javascript">
$(document).ready(function(){
$('a[data-toggle="tab"]').on('show.affectedDiv.tab', function(e) {
localStorage.setItem('activeTab', $(e.target).attr('href'));
});
var activeTab = localStorage.getItem('activeTab');
if(activeTab){
$('#myTab a[href="' + activeTab + '"]').tab('show');
}
});
</script>
and here is the code for bootstrap tabs:
<div class="affectedDiv">
<ul class="nav nav-tabs" id="myTab">
<li class="active"><a data-toggle="tab" href="#sectionA">Section A</a></li>
<li><a data-toggle="tab" href="#sectionB">Section B</a></li>
<li><a data-toggle="tab" href="#sectionC">Section C</a></li>
</ul>
<div class="tab-content">
<div id="sectionA" class="tab-pane fade in active">
<h3>Section A</h3>
<p>Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui. Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth.</p>
</div>
<div id="sectionB" class="tab-pane fade">
<h3>Section B</h3>
<p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
</div>
<div id="sectionC" class="tab-pane fade">
<h3>Section C</h3>
<p>Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna, ornare id gravida ut, mollis a magna. Aliquam porttitor condimentum nisi, eu viverra ipsum porta ut. Nam hendrerit bibendum turpis, sed molestie mi fermentum id. Aenean volutpat velit sem. Sed consequat ante in rutrum convallis. Nunc facilisis leo at faucibus adipiscing.</p>
</div>
</div>
</div>
Dont forget to call the bootstrap and other fundamental things
here are quick codes for you:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Now let's come to the explanation:
The jQuery code in the above example simply gets the element's href attribute value when a new tab has been shown using the jQuery .attr() method and save it locally in the user's browser through HTML5 localStorage object. Later, when the user refresh the page it retrieves this data and activate the related tab via .tab('show') method.
Looking up for some examples? here is one for you guys.. https://jsfiddle.net/Wineson123/brseabdr/
I wish my answer could help you all.. Cheerio! :)
My code, it work for me, I use localStorage
HTML5
$('#tabHistory a').click(function(e) {
e.preventDefault();
$(this).tab('show');
});
$("ul.nav-tabs#tabHistory > li > a").on("shown.bs.tab", function(e) {
var id = $(e.target).attr("href");
localStorage.setItem('selectedTab', id)
});
var selectedTab = localStorage.getItem('selectedTab');
$('#tabHistory a[href="' + selectedTab + '"]').tab('show');
Basing myself on answers provided by Xavi Martínez and koppor I came up with a solution that uses the url hash or localStorage depending on the availability of the latter:
function rememberTabSelection(tabPaneSelector, useHash) {
var key = 'selectedTabFor' + tabPaneSelector;
if(get(key))
$(tabPaneSelector).find('a[href=' + get(key) + ']').tab('show');
$(tabPaneSelector).on("click", 'a[data-toggle]', function(event) {
set(key, this.getAttribute('href'));
});
function get(key) {
return useHash ? location.hash: localStorage.getItem(key);
}
function set(key, value){
if(useHash)
location.hash = value;
else
localStorage.setItem(key, value);
}
}
Usage:
$(document).ready(function () {
rememberTabSelection('#rowTab', !localStorage);
// Do Work...
});
It does not keep up with the back button as is the case for Xavi Martínez's solution.
We used jquery trigger to onload have a script hit the button for us
$(".class_name").trigger('click');
Woe, there's so many ways to do this. I came up with this, short and simple. Hope this help others.
var url = document.location.toString();
if (url.match('#')) {
$('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
}
$('.nav-tabs a').on('shown.bs.tab', function (e) {
window.location.hash = e.target.hash;
if(e.target.hash == "#activity"){
$('.nano').nanoScroller();
}
})
This is the best one that I tried:
$(document).ready(function() {
if (location.hash) {
$("a[href='" + location.hash + "']").tab("show");
}
$(document.body).on("click", "a[data-toggle='tab']", function(event) {
location.hash = this.getAttribute("href");
});
});
$(window).on("popstate", function() {
var anchor = location.hash || $("a[data-toggle='tab']").first().attr("href");
$("a[href='" + anchor + "']").tab("show");
});
In addition to Xavi Martínez's answer avoiding the jump on click
Avoiding Jump
$(document).ready(function(){
// show active tab
if(location.hash) {
$('a[href=' + location.hash + ']').tab('show');
}
// set hash on click without jumb
$(document.body).on("click", "a[data-toggle]", function(e) {
e.preventDefault();
if(history.pushState) {
history.pushState(null, null, this.getAttribute("href"));
}
else {
location.hash = this.getAttribute("href");
}
$('a[href=' + location.hash + ']').tab('show');
return false;
});
});
// set hash on popstate
$(window).on('popstate', function() {
var anchor = location.hash || $("a[data-toggle=tab]").first().attr("href");
$('a[href=' + anchor + ']').tab('show');
});
Nested tabs
implementation with "_" character as separator
$(document).ready(function(){
// show active tab
if(location.hash) {
var tabs = location.hash.substring(1).split('_');
$.each(tabs,function(n){
$('a[href=#' + tabs[n] + ']').tab('show');
});
$('a[href=' + location.hash + ']').tab('show');
}
// set hash on click without jumb
$(document.body).on("click", "a[data-toggle]", function(e) {
e.preventDefault();
if(history.pushState) {
history.pushState(null, null, this.getAttribute("href"));
}
else {
location.hash = this.getAttribute("href");
}
var tabs = location.hash.substring(1).split('_');
//console.log(tabs);
$.each(tabs,function(n){
$('a[href=#' + tabs[n] + ']').tab('show');
});
$('a[href=' + location.hash + ']').tab('show');
return false;
});
});
// set hash on popstate
$(window).on('popstate', function() {
var anchor = location.hash || $("a[data-toggle=tab]").first().attr("href");
var tabs = anchor.substring(1).split('_');
$.each(tabs,function(n){
$('a[href=#' + tabs[n] + ']').tab('show');
});
$('a[href=' + anchor + ']').tab('show');
});
I tried the code offered by Xavi Martínez. It worked but not for IE7. The problem is - tabs don't refer to any relevant content.
So, I prefer this code for solving that problem.
function pageLoad() {
$(document).ready(function() {
var tabCookieName = "ui-tabs-1"; //cookie name
var location = $.cookie(tabCookieName); //take tab's href
if (location) {
$('#Tabs a[href="' + location + '"]').tab('show'); //activate tab
}
$('#Tabs a').click(function(e) {
e.preventDefault()
$(this).tab('show')
})
//when content is alredy shown - event activate
$('#Tabs a').on('shown.bs.tab', function(e) {
location = e.target.hash; // take current href
$.cookie(tabCookieName, location, {
path: '/'
}); //write href in cookie
})
});
};
I tried this and it works: ( Please replace this with the pill or tab you are using )
jQuery(document).ready(function() {
jQuery('a[data-toggle="pill"]').on('show.bs.tab', function(e) {
localStorage.setItem('activeTab', jQuery(e.target).attr('href'));
});
// Here, save the index to which the tab corresponds. You can see it
// in the chrome dev tool.
var activeTab = localStorage.getItem('activeTab');
// In the console you will be shown the tab where you made the last
// click and the save to "activeTab". I leave the console for you to
// see. And when you refresh the browser, the last one where you
// clicked will be active.
console.log(activeTab);
if (activeTab) {
jQuery('a[href="' + activeTab + '"]').tab('show');
}
});
I hope it would help somebody.
Here is the result: https://jsfiddle.net/neilbannet/ego1ncr5/5/
There is a solution after reloading the page and keeping the expected tab as selected.
Suppose after saving data the redirected url is : my_url#tab_2
Now through the following script your expected tab will remain selected.
$(document).ready(function(){
var url = document.location.toString();
if (url.match('#')) {
$('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
$('.nav-tabs a').removeClass('active');
}
});
A mix between others answers:
Just copy&paste ;)
if (location.hash) {
$('a[href=\'' + location.hash + '\']').tab('show');
}
var activeTab = localStorage.getItem('activeTab');
if (activeTab) {
$('a[href="' + activeTab + '"]').tab('show');
}
$('body').on('click', 'a[data-toggle=\'tab\']', function (e) {
e.preventDefault()
var tab_name = this.getAttribute('href')
if (history.pushState) {
history.pushState(null, null, tab_name)
}
else {
location.hash = tab_name
}
localStorage.setItem('activeTab', tab_name)
$(this).tab('show');
return false;
});
$(window).on('popstate', function () {
var anchor = location.hash ||
$('a[data-toggle=\'tab\']').first().attr('href');
$('a[href=\'' + anchor + '\']').tab('show');
});
Using html5 I cooked up this one:
Some where on the page:
<h2 id="heading" data-activetab="@ViewBag.activetab">Some random text</h2>
The viewbag should just contain the id for the page/element eg.: "testing"
I created a site.js and added the scrip on the page:
/// <reference path="../jquery-2.1.0.js" />
$(document).ready(
function() {
var setactive = $("#heading").data("activetab");
var a = $('#' + setactive).addClass("active");
}
)
Now all you have to do is to add your id's to your navbar. Eg.:
<ul class="nav navbar-nav">
<li **id="testing" **>
@Html.ActionLink("Lalala", "MyAction", "MyController")
</li>
</ul>
All hail the data attribute :)
This one use HTML5 localStorage
to store active tab
$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
localStorage.setItem('activeTab', $(e.target).attr('href'));
});
var activeTab = localStorage.getItem('activeTab');
if (activeTab) {
$('#navtab-container a[href="' + activeTab + '"]').tab('show');
}
ref: http://www.tutorialrepublic.com/faq/how-to-keep-the-current-tab-active-on-page-reload-in-bootstrap.php https://www.w3schools.com/bootstrap/bootstrap_ref_js_tab.asp
Since I cannot comment yet I copied the answer from above, it really helped me out. But I changed it to work with cookies instead of #id so I wanted to share the alterations. This makes it possible to store the active tab longer than just one refresh (e.g. multiple redirect) or when the id is already used and you don't want to implement koppors split method.
<ul class="nav nav-tabs" id="myTab">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#profile">Profile</a></li>
<li><a href="#messages">Messages</a></li>
<li><a href="#settings">Settings</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="home">home</div>
<div class="tab-pane" id="profile">profile</div>
<div class="tab-pane" id="messages">messages</div>
<div class="tab-pane" id="settings">settings</div>
</div>
<script>
$('#myTab a').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function (e) {
var id = $(e.target).attr("href").substr(1);
$.cookie('activeTab', id);
});
// on load of the page: switch to the currently selected tab
var hash = $.cookie('activeTab');
if (hash != null) {
$('#myTab a[href="#' + hash + '"]').tab('show');
}
</script>
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):
$('a[data-toggle="tab"]').click(function (e) {
e.preventDefault();
$(this).tab('show');
});
$('a[data-toggle="tab"]').on("shown.bs.tab", function (e) {
var id = $(e.target).attr("href");
localStorage.setItem('selectedTab', id)
});
var selectedTab = localStorage.getItem('selectedTab');
if (selectedTab != null) {
$('a[data-toggle="tab"][href="' + selectedTab + '"]').tab('show');
}
Source: Stackoverflow.com