James A Mohler
James A Mohler

Reputation: 11120

Go to Specific Tab on Page Reload or Hyperlink where tab is loaded by AJAX

I have a set of Bootstrap tabs.

HTML

<ul class="nav nav-tabs" role="tablist">
    <li class="active"><a href="#main" role="tab" data-toggle="tab" data-url="~/ccf/main">Main</a></li>
    <li><a href="#userinfo" role="tab" data-toggle="tab" data-url="~/ccf/userinfo">User Info</a></li>

   ...
</ul>

<div class="tab-content">
  <div class="tab-pane active" id="main"></div>
  <div class="tab-pane" id="userinfo"></div>
  ...
</div>

JS

var url = document.location.toString();
if (url.match('#')) {
    $('.nav-tabs a[href=#' + url.split('#')[1] + ']').tab('show');
}

// Change hash for page-reload
$('.nav-tabs a').on('shown', function (e) {
    window.location.hash = e.target.hash;
})


// load first tab content if it is AJAX
$('#main').load($('a[data-url]:first').attr("data-url") +  "&silent=1", function (data) {
    $('.active a').tab('show');
});

What I want is for the what ever tab has focus to be loaded, rather than always load the first.

Update: I am getting the tab to focus. It just doesn't fire off the AJAX load

This is not the same as Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

Upvotes: 2

Views: 1881

Answers (1)

Leandro Carracedo
Leandro Carracedo

Reputation: 7345

The only way to go to the last tab that has the focus, is to store a reference (using cookies or local storage).

This code uses local storage to store the href value of the focused tab and later retrieve it.

$(function() { 
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        localStorage.setItem('focustab', $(e.target).attr('href'));
    });

    var focustab = localStorage.getItem('focustab');
    if (focustab) {
        $('[href="' + focustab + '"]').tab('show');
    }
});

Upvotes: 2

Related Questions