Rocstar
Rocstar

Reputation: 1477

Load ajax content when keep active tab after page reload (Bootstrap 4)

I created a page with many tabs In order not to slow down the loading of the page during the first display, I get the content of the tabs only if we click on it

I then set this up to save the last active tab :

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

var activeTab = localStorage.getItem('activeTab');
if(activeTab){
    $('.nav-tabs a[href="' + activeTab + '"]').tab('show');
}

It works well, when I reload the page I fall well on the last tab visited

But problem, it does not load Ajax content (or even a simple alert)

DEMO : https://jsfiddle.net/ak37besp/1/

How to get to the last tab used and then load the corresponding Ajax ?

Upvotes: 0

Views: 759

Answers (1)

Fala
Fala

Reputation: 566

The problem in your code is that you're not calling any function that loads the ajax content after you reload the page, you're only setting the active tab.

to do that, create a function in your code called loadTabContent(tab) that takes the tab id as a parameter and load the ajax content:

function loadTabContent(tab) {
    if (tab == '#tab2'){
    alert("ajax loaded tab2");
    //load ajax content for tab 2 here
  }
}

And then when checking and setting an active tab from localStorage, call the created function:

// read hash from page load and change tab
var activeTab = localStorage.getItem('activeTab');
if(activeTab){
  $('.nav-tabs a[href="' + activeTab + '"]').tab('show');
  loadTabContent(activeTab);
}

And here's a demo link: https://jsfiddle.net/1mfqwgpz/3/

Upvotes: 1

Related Questions