Created
June 5, 2012 14:43
-
-
Save badsyntax/2875426 to your computer and use it in GitHub Desktop.
Twitter bootstrap tabs & jQuery BBQ hashchange history example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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' ); | |
}); |
In case anyone else got caught in a history loop - replace line 33 with
$(this).find( tab_a_selector ).eq( idx ).tab('show');
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
This is very cool - however I get a problem that creates two history entries when I land on a page with tabs on it so the back button won't work to go back past the tabbed page. Do you have a workaround for this?