ArticleZip > Twitter Bootstrap Tabs Go To Specific Tab On Page Reload Or Hyperlink

Twitter Bootstrap Tabs Go To Specific Tab On Page Reload Or Hyperlink

Are you looking to dive deeper into the world of Twitter Bootstrap tabs but finding it tricky to navigate to a specific tab when you reload the page or click on a hyperlink? Never fear! I've got your back with some handy tips on how to make those tabs work just the way you want them to.

First things first, let's talk about the basics of Twitter Bootstrap tabs. Tabs are a great way to organize content on your webpage, allowing users to switch between different sections easily. However, if you want to ensure that a specific tab stays open even after the page is reloaded or when a link is clicked, a little extra tweaking is needed.

To make a Twitter Bootstrap tab go to a specific tab on a page reload or hyperlink, you need to leverage a combination of JavaScript and HTML. One of the most straightforward methods is by modifying the URL hash in the browser address bar. When a tab is activated, its corresponding tab ID is added to the URL as a hash, allowing you to bookmark or share that specific tab.

Here's a step-by-step guide to achieving this functionality:

1. Start by assigning unique IDs to each tab pane in your HTML markup:

Html

<div class="tab-content">
  <div class="tab-pane active" id="tab1">Tab 1 content</div>
  <div class="tab-pane" id="tab2">Tab 2 content</div>
  <div class="tab-pane" id="tab3">Tab 3 content</div>
</div>

2. In your JavaScript code, check for the hash in the URL and show the corresponding tab:

Javascript

$(document).ready(function() {
  var hash = window.location.hash;
  if (hash) {
    $('.nav-tabs a[href="' + hash + '"]').tab('show');
  }
  
  $('.nav-tabs a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash;
  });
});

3. Don't forget to add hash links to your tab navigation:

Html

<ul class="nav nav-tabs" role="tablist">
  <li role="presentation" class="active"><a href="#tab1" aria-controls="tab1" role="tab" data-toggle="tab">Tab 1</a></li>
  <li role="presentation"><a href="#tab2" aria-controls="tab2" role="tab" data-toggle="tab">Tab 2</a></li>
  <li role="presentation"><a href="#tab3" aria-controls="tab3" role="tab" data-toggle="tab">Tab 3</a></li>
</ul>

With this setup, your tabs will now retain their state even when the page is reloaded or when users navigate using hyperlinks. Users can easily share links that directly open a specific tab, enhancing the usability of your page.

By following these simple steps, you can harness the power of Twitter Bootstrap tabs to create a seamless user experience on your website. So go ahead, give it a try, and watch your tabs work like a charm every time!