Save Ukraine

Twitter Bootstrap: how to fix tabs

Christian Kruse,

I use Twitter's Bootstrap in my day to day work, and I'm pretty satisfied with it. It works, solves loads of problems and brings a rich set of UI elements.

But one thing annoys me every time I have to use it: tabs. They simply do not work with the browser history, you cannot go back to a page and have the old tab open or go back to a tab. I think this is a huge usability issue. Gladly, it can be fixed with a few lines of JavaScript:

$(document).ready(function() {
/* Automagically jump on good tab based on anchor; for page reloads or links */
if(location.hash) {
$('a[href=' + location.hash + ']').tab('show');

/* Update hash based on tab, basically restores browser default behavior to fix bootstrap tabs */ $(document.body).on("click", "a[data-toggle]", function(event) { location.hash = this.getAttribute("href"); }); });

/* on history back activate the tab of the location hash if exists or the default tab if no hash exists */ $(window).on('popstate', function() { var anchor = location.hash || $("a[data-toggle=tab]").first().attr("href"); $('a[href=' + anchor + ']').tab('show'); });

Basically, every time you open a tab it sets the document hash to the tab hash and so generates a new history entry – we restore the browser default behavior. To achieve history back behavior in tabs, we use the history API: on a popstate event we activate the tab of the anchor or the default tab if no hash is set.

Works pretty well for me.