There is also a simple way to react on hash changes (e.g. back button). Simply add an hashchange event listener to tomaszbak solution:
$(function(){
// Change tab on load
var hash = window.location.hash;
hash && $('ul.nav a[href="' + hash + '"]').tab('show');
$('.nav-tabs a').click(function (e) {
$(this).tab('show');
var scrollmem = $('body').scrollTop();
window.location.hash = this.hash;
$('html,body').scrollTop(scrollmem);
});
// Change tab on hashchange
window.addEventListener('hashchange', function() {
var changedHash = window.location.hash;
changedHash && $('ul.nav a[href="' + changedHash + '"]').tab('show');
}, false);
});
As your anchor elements already change the url hash, listening to onhashchange event is another good option. As @flori already mentioned, this method works nice with the browser back button.
var tabs$ = $(".nav-tabs a");
$( window ).on("hashchange", function() {
var hash = window.location.hash, // get current hash
menu_item$ = tabs$.filter('[href="' + hash + '"]'); // get the menu element
menu_item$.tab("show"); // call bootstrap to show the tab
}).trigger("hashchange");
Finally, triggering the event just after you define the listener will also help showing the right tab on page load.
Most simple, assuming you're using the documented data-toggle="tab"
syntax described here:
$(document).on('shown.bs.tab', function(event) {
window.location.hash = $(event.target).attr('href');
});