Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

I'm developing a web page in which I'm using Twitter's Bootstrap Framework and their Bootstrap Tabs JS. It works great except for a few minor issues, one of which is I do not know how go directly to a specific tab from an external link. For example:

<a href="facility.php#home">Home</a> <a href="facility.php#notes">Notes</a> 

should go to the Home tab and the Notes tab respectively when clicked on the links from an external page

like image 647
mraliks Avatar asked Oct 22 '11 20:10

mraliks


2 Answers

Here is my solution to the problem, a bit late perhaps. But it could maybe help others:

// Javascript to enable link to tab var hash = location.hash.replace(/^#/, '');  // ^ means starting, meaning only match the first hash if (hash) {     $('.nav-tabs a[href="#' + hash + '"]').tab('show'); }   // Change hash for page-reload $('.nav-tabs a').on('shown.bs.tab', function (e) {     window.location.hash = e.target.hash; }) 
like image 137
dubbe Avatar answered Sep 21 '22 07:09

dubbe


UPDATE

For Bootstrap 3, change .on('shown', ...) to .on('shown.bs.tab', ....)


This is based off of @dubbe answer and this SO accepted answer. It handles the issue with window.scrollTo(0,0) not working correctly. The problem is that when you replace the url hash on tab shown, the browser will scroll to that hash since its an element on the page. To get around this, add a prefix so the hash doesn't reference an actual page element

// Javascript to enable link to tab var hash = document.location.hash; var prefix = "tab_"; if (hash) {     $('.nav-tabs a[href="'+hash.replace(prefix,"")+'"]').tab('show'); }   // Change hash for page-reload $('.nav-tabs a').on('shown', function (e) {     window.location.hash = e.target.hash.replace("#", "#" + prefix); }); 

Example of use

If you have tab-pane with id="mytab" you need to put your link like this:

<a href="yoursite.com/#tab_mytab">Go to Specific Tab </a> 
like image 43
flynfish Avatar answered Sep 22 '22 07:09

flynfish