keep the current tab active with twitter bootstrap after a page reload?

As Tommi Komulainen wrote: e.target contains the full url including the hash. You only need the hash. So use e.target.toString().split('#')[1]); or even better $(this).attr('href')
$('#'+lastTab).tab('show'); applies the .tab() on the div with id = #{lastTab} while you need to apply on the link (a tag) with data-toggle. So use: $('a[href=#"https://stackoverflow.com/questions/16808205/+ lastTab +"]').tab('show'); here.

The complete function to use:

                  $(function() 
                    { 
                      $('a[data-toggle="tab"]').on('shown', function () {
                        //save the latest tab; use cookies if you like 'em better:
                        localStorage.setItem('lastTab', $(this).attr('href'));
                       });

                      //go to the latest tab, if it exists:
                      var lastTab = localStorage.getItem('lastTab');
                      if (lastTab) {
                         $('a[href="https://stackoverflow.com/questions/16808205/+ lastTab +"]').tab('show');
                      }
                      else
                      {
                        // Set the first tab if cookie do not exist
                        $('a[data-toggle="tab"]:first').tab('show');
                      }
                  });

update:
see https://stackoverflow.com/a/16016592/1596547 so remove the active class from your source and set the first tab active when lastTab is not set.

Leave a Comment