Bootstrap 3: Keep selected tab on page refresh

JqueryTwitter BootstrapTabsTwitter Bootstrap-3

Jquery Problem Overview


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');
}

Jquery Solutions


Solution 1 - Jquery

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.

<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>

JavaScript, has to be embedded after the above in a <script>...</script> part.

$('#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);
  window.location.hash = id;
});

// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
$('#myTab a[href="' + hash + '"]').tab('show');

Solution 2 - Jquery

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");
});

Solution 3 - Jquery

A mix between others answers:

  • No jump on click

  • Save on location hash

  • Save on localStorage (e.g: for form submit)

  • 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');
      });
    

Solution 4 - Jquery

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');
}

Solution 5 - Jquery

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

Solution 6 - Jquery

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! :)

Solution 7 - Jquery

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.

Solution 8 - Jquery

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');

Solution 9 - Jquery

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/

Solution 10 - Jquery

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>

Solution 11 - Jquery

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
    })
  });
};

Solution 12 - Jquery

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');
});

Solution 13 - Jquery

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');
	}
});

Solution 14 - Jquery

> 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');
    }
});

Solution 15 - Jquery

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');
})

Solution 16 - Jquery

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 :)

Solution 17 - Jquery

We used jquery trigger to onload have a script hit the button for us

$(".class_name").trigger('click');

Solution 18 - Jquery

There's so many ways to do this. I came up with this, short and simple.

  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();
    }
  })

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCode LoverView Question on Stackoverflow
Solution 1 - JquerykopporView Answer on Stackoverflow
Solution 2 - JqueryXavi MartínezView Answer on Stackoverflow
Solution 3 - JqueryinsignView Answer on Stackoverflow
Solution 4 - JqueryapfzView Answer on Stackoverflow
Solution 5 - JqueryAjith R NairView Answer on Stackoverflow
Solution 6 - JqueryMr. WinsonView Answer on Stackoverflow
Solution 7 - JqueryZiadView Answer on Stackoverflow
Solution 8 - JqueryNguyen PhamView Answer on Stackoverflow
Solution 9 - JqueryNobodyView Answer on Stackoverflow
Solution 10 - JqueryJoeri LandmanView Answer on Stackoverflow
Solution 11 - JqueryVitalii IsaenkoView Answer on Stackoverflow
Solution 12 - JqueryRafaSashiView Answer on Stackoverflow
Solution 13 - JqueryVaibhavView Answer on Stackoverflow
Solution 14 - JqueryHasib Kamal ChowdhuryView Answer on Stackoverflow
Solution 15 - Jquerygkc123View Answer on Stackoverflow
Solution 16 - JqueryTheodor Alexander Hkansson HeiView Answer on Stackoverflow
Solution 17 - JqueryDan KaiserView Answer on Stackoverflow
Solution 18 - Jqueryuser752746View Answer on Stackoverflow