Home > other >  Remember the last selected tab with localstorage
Remember the last selected tab with localstorage

Time:01-06

In a bootstrap 4 website, I have the tabs below:

<ul id="tabsJustified" >
    <li ><a href="#tab1" data-target="#tab1" data-toggle="tab" >Personal details</a></li>
    <li ><a href="#tab2" data-target="#tab2" data-toggle="tab" >Medical conditions</a></li>
    <li ><a href="#tab3" data-target="#tab3" data-toggle="tab" >Medication</a></li>
    <li ><a href="#tab4" data-target="#tab4" data-toggle="tab" >Care needs</a></li>
    <li ><a href="#tab4" data-target="#tab5" data-toggle="tab" >Care environment</a></li>
    <li ><a href="#tab3" data-target="#tab6" data-toggle="tab" ><i ></i>Add a second client</a></li>
</ul>

What I want is, remember the last selected tab and when the page reloads, go to that tab.

With this code, it's only working with the 1st, 2nd and 6th tab.

$(function() { 
    $('a[data-toggle="tab"]').on('shown.bs.tab', function () {
        localStorage.setItem('lastTab', $(this).attr('href'));
    });
    var lastTab = localStorage.getItem('lastTab');
    if (lastTab) {
        $('[href="'   lastTab   '"]').tab('show');
        console.log(lastTab);
    }
});

When I click the 4th tab, after reload, the 5th tab will be active. The console.log row gives back the correct tab id or href, I checked that.

CodePudding user response:

Hmm, check your href values, you have incorrect increment "1, 2, 3, 4, 4, 3", because you have "4" twice, that is why fifth is selected.

Just change it to "1, 2, 3, 4, 5, 6"

enter image description here

  •  Tags:  
  • Related