Enable Back Button Handling With Twitter Bootstrap Tabs Plugin

Twitter Bootstrap offers a neat plugin called Tabs, to add "quick, dynamic tab and pill functionality for transitioning through local content". The problem is that this plugin doesn't support back button navigation. In other terms, if you switch tabs and then go to another page, a click on the back button of your browser brings you back to the first open tab, not the last open one.

Yuck.

Unfortunately, the author of the plugin doesn't want to support this, as it's impossible to implement in a cross-browser way.

But if you don't mind leaving behind all the IE7 users and go the HTML5 way - for instance for a backend interface with limited access - then it's pretty easy to implement. Thanks to the new HTML5 history API, you can manipulate the browser history to fit your needs. Implementing back button navigation to a Twitter Bootstrap tab then becomes easy:

$(document).ready(function() {
// add a hash to the URL when the user clicks on a tab
$('a[data-toggle="tab"]').on('click', function(e) {
history.pushState(null, null, $(this).attr('href'));
});
// navigate to a tab when the history changes
window.addEventListener("popstate", function(e) {
var activeTab = $('[href=' + location.hash + ']');
if (activeTab.length) {
activeTab.tab('show');
} else {
$('.nav-tabs a:first').tab('show');
}
});
});
view raw gistfile1.js hosted with ❤ by GitHub

It took me a while to figure out how to implement this feature for Uptime, the remote monitoring tool written in Node.js, so I hope someone will find this useful.

For more information about this new HTML5 API, I recommend these two links:

Published on 17 May 2012 with tags JavaScript