jentanbernardus
6/5/2012 - 2:43 PM

Twitter bootstrap tabs & jQuery BBQ hashchange history example

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' );
});