Skip to content

Instantly share code, notes, and snippets.

@virusman
Created September 25, 2012 10:31
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save virusman/3781093 to your computer and use it in GitHub Desktop.
Save virusman/3781093 to your computer and use it in GitHub Desktop.
Twitter Bootstrap Tabs + History.js - made as jQuery plugin
$(document).ready(function() {
//init tab history with default tab 'table'
$(window).tabHistory('table');
});
$.fn.tabHistory = function(defaultTab, selectorPrefix){
// Handle tabs, page reloads & browser forward/back history.
var History = window.History;
if(!selectorPrefix) selectorPrefix = '.navbar li > ';
if (!History.enabled) {
return false;
}
$(window).bind('load statechange', function (event) {
var State = History.getState();
var hash = History.getHash();
// Our default tab.
if (!State.data || !State.data.tab) {
if (hash) {
State.data.tab = hash;
window.location.hash = '';
} else {
State.data.tab = defaultTab;
}
}
$(selectorPrefix+'a[href="#' + State.data.tab + '"]').tab('show');
if(event.type == 'load')
History.replaceState({tab: State.data.tab}, null, State.url);
});
$('a[data-toggle="tab"]').on('shown', function (event) {
// Set the selected tab to be the current state. But don't update the URL.
var url = event.target.href.split("#")[0];
var tab = event.target.href.split("#")[1];
var State = History.getState();
// Don't set the state if we haven't changed tabs.
if (State.data.tab != tab) {
History.pushState({'tab': tab}, null, url);
}
});
};
@daveo1001
Copy link

So, lets say I'm a total dummy and I'm trying to get this to work. I include jq-bootstrap-tab-history.js, the example (adjusted with the id of my default tab?) and history.js and then it just works? :/ Do I want to use the jquery.history.js. Is there some not-worth-mentioning piece of information that that a normal person wouldn't need?

Copy link

ghost commented Aug 6, 2013

You need to include the twitter bootstrap tabs .js file too - as well as the css needed to show/hide tabs

http://getbootstrap.com/javascript/#tabs

@williamparry
Copy link

For new Bootstrap 3 RC1

Update line 29 (jq-bootstrap-tab-history.js)

$('a[data-toggle="tab"]').on('shown.bs.tab', function (event) {

Update the selector (example.js)

$(window).tabHistory('table', '.navbar-nav');

Because the selector overrides the default you need to add a space to line 24 (jq-bootstrap-tab-history.js)

$(selectorPrefix+' a[href="#' + State.data.tab + '"]').tab('show');

I recommend against having a space in the selector argument (as handled on line 4 of jq-bootstrap-tab-history.js)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment