Skip to content

Instantly share code, notes, and snippets.

@badsyntax
Created June 5, 2012 14:43
Show Gist options
  • Save badsyntax/2875426 to your computer and use it in GitHub Desktop.
Save badsyntax/2875426 to your computer and use it in GitHub Desktop.
Twitter bootstrap tabs & jQuery BBQ hashchange history example
<!-- Tab sets have to have an id set -->
<div class="tabs" id="mytab1">
<ul class="nav nav-tabs">
<li><a href="#tab1">Tab 1</a></li>
<li><a href="#tab2">Tab 2</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="tab1">
Content for tab 1
</div>
<div class="tab-pane" id="tab2">
Content for tab 2
</div>
</div>
</div>
/**
* This example shows how to use the jQuery BBQ hashchange plugin with Twitter bootstrap tabs plugin.
* This code is a modified version of the jQuery UI tabs example found on this page: http://benalman.com/code/projects/jquery-bbq/examples/fragment-jquery-ui-tabs/
* jQuery BBQ: http://benalman.com/projects/jquery-bbq-plugin/
*/
$(function(){
var tabs = $('.tabs'),
tab_a_selector = '.nav-tabs a';
tabs.find( tab_a_selector ).click(function(e){
e.preventDefault();
$(this).tab('show');
var state = {},
// Get the id of this tab widget.
id = $(this).closest( '.tabs' ).attr( 'id' ),
// Get the index of this tab.
idx = $(this).parent().prevAll().length;
// Set the state!
state[ id ] = idx;
$.bbq.pushState( state );
});
$(window)
.on( 'hashchange', function(e) {
tabs.each(function(){
var idx = $.bbq.getState( this.id, true ) || 0;
$(this).find( tab_a_selector ).eq( idx ).triggerHandler( 'click' );
});
})
.trigger( 'hashchange' );
});
@marine44
Copy link

Great Script! Do you know how to format the URL differently.

I was hoping for something like: /clients/1#contacts

At present I am getting: /clients/1#tab=0

Thanks again for posting this!!!

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