Twitter Bootstrap - Tabs - URL doesn't change

Try this code. It adds tab href to url + opens tab based on hash on page load:

$(function(){
  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() || $('html').scrollTop();
    window.location.hash = this.hash;
    $('html,body').scrollTop(scrollmem);
  });
});

There are three components necessary for a complete solution:

  1. Show the correct tab when the page is loaded if there is a hash in the URL.
  2. Changing the hash in the URL when the tab is changed.
  3. Change the tab when the hash changes in the URL (back / forward buttons), and make sure the first tab is cycled correctly.

I don't think any of the comments here, nor the accepted answer, handle all of these scenarios.

As there's quite a bit involved, I think it's neatest as a small jQuery plugin: https://github.com/aidanlister/jquery-stickytabs

You can call the plugin like so:

$('.nav-tabs').stickyTabs();

I've made a blog post for this, http://aidanlister.com/2014/03/persisting-the-tab-state-in-bootstrap/


Using data-toggle="tab" asks the plugin to handle the tabs, which while doing it calls preventDefault on the event (code on github).

You can use your own tab activation, and let the event go through :

$('.nav-tabs a').click(function (e) {
    // No e.preventDefault() here
    $(this).tab('show');
});

And you must remove the attribute data-toggle="tab"

Check the doc if you have doubts.