Explain Codes LogoExplain Codes Logo

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

javascript
prompt-engineering
responsive-design
performance
Alex KataevbyAlex Kataev·Sep 21, 2024
TLDR

Activate a Twitter Bootstrap tab from a URL hash employing jQuery:

$(document).ready(function() { if(window.location.hash){ // Not just another URL hash $('a[href="' + window.location.hash + '"]').tab('show'); } else { // Rock, paper, scissors, first tab! $('a[data-toggle="tab"]:first').tab('show'); } });

Synchronize each tab's href with your content's ID. To highlight the related tab, visit yourpage.html#tabID.

Handling URL hash updates with elegance

Switching tabs smoothly needs a few enchantments in your JavaScript sorcery:

$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) { // Life's a-hashin' window.location.hash = e.target.hash; // We like it at the top, and so does our page window.scrollTo(0, 0); });

Handle the shown.bs.tab event to track the URL with the active tab. The chief idea is simple, maintain tab focus and stop the abrupt "jump" to the tab content.

Greater finesse with HTML5 and localStorage

Craft a software masterpiece with HTML5's history API, and your tabs will remember each visit:

$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) { if(history.pushState) { // Setting memory without forgetting the past history.pushState(null, null, e.target.hash); } else { window.location.hash = e.target.hash; } });

With localStorage you can script them to remember which tab was last glorified:

$(document).ready(function() { var activeTab = localStorage.getItem('activeTab'); // You shall not forget the chosen one if (activeTab) { $('a[href="' + activeTab + '"]').tab('show'); } }); $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) { // The chosen one gets the crown localStorage.setItem('activeTab', e.target.hash); });

Now, tabs retain attention, irrespective of whether the browser or tab is resurrected.

Strategize around known challenges

Stop scrolling in its tracks

When your tabs are far into the page abyss, prefixing the hash stops the scroll:

window.location.hash = "tab_" + e.target.hash;

Sustain smooth scrolling while maintaining tab focus.

Employ URL parameters with server-side rendering

Adjust server-rendered views to shine with dynamism:

// When life gives you parameters, make activeTabs let params = new URLSearchParams(window.location.search); let activeTab = params.get('activeTab'); if(activeTab){ $('a[href="#' + activeTab + '"]').tab('show'); }

Experience instant transitions on server-heavy apps with the power of query parameters.

Account for missing hash

If the URL is hash-less, prepare a default tab:

if(!window.location.hash) { $('a[data-toggle="tab"]:first').tab('show'); }

Establish a consistent point of origin for those curious first-time visitors or in instances of missing hashes.