简体   繁体   中英

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 ?

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM