Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to make Twitter Bootstrap tabs persistent

What is the best way of making these tabs persist?

http://twitter.github.com/bootstrap/javascript.html#tabs

To add some context, this is for a Ruby on Rails application. I'm passing an array [tab1, tab2] to my view, rendering both tabs and using the Bootstrap tab plugin to toggle their visibility.

like image 681
DanS Avatar asked Mar 13 '12 14:03

DanS


2 Answers

This code selects the right tab depending on the #hash and adds the right #hash when a tab is clicked. (this uses jQuery)

In CoffeeScript:

$(document).ready ->     if location.hash != ''          $('a[href="'+location.hash+'"]').tab('show')      $('a[data-toggle="tab"]').on 'shown', (e) ->         location.hash = $(e.target).attr('href').substr(1) 

Or in JavaScript:

$(document).ready(function() {     if (location.hash !== '') $('a[href="' + location.hash + '"]').tab('show');     return $('a[data-toggle="tab"]').on('shown', function(e) {       return location.hash = $(e.target).attr('href').substr(1);     }); }); 
like image 95
Sucrenoir Avatar answered Oct 15 '22 02:10

Sucrenoir


I wanted to improve the best answer here...

Credit goes to Sucrenoir, but if you want to avoid jumping on the page when you change tabs, use this improved code:

$(document).ready(function() {      // Show active tab on reload     if (location.hash !== '') $('a[href="' + location.hash + '"]').tab('show');      // Remember the hash in the URL without jumping     $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {        if(history.pushState) {             history.pushState(null, null, '#'+$(e.target).attr('href').substr(1));        } else {             location.hash = '#'+$(e.target).attr('href').substr(1);        }     }); }); 
like image 24
d-wade Avatar answered Oct 15 '22 00:10

d-wade