Home > Blockchain >  How can I keep selected tab active on page refresh?
How can I keep selected tab active on page refresh?

Time:06-28

My code is not working. This code is basically for keeping active current selected page or tab on page refresh or page reload.

HTML code:

<section id="sidebar" >
<a href="#" >
    <!-- <i class='bx bxs-smile'></i> -->
    <span ><img src="images/logo.png" alt="" ></span>
</a>
<ul  id="myTab">
    <li >
        <a href="#dashboard" data-toggle="tab" data-index=1>
            <i class='bx bxs-dashboard'></i>
            <span >Dashboard</span>
        </a>
    </li>
    <li>
        <a href="#1a" data-toggle="tab" data-index=2>
            <i class='bx bxs-dashboard'></i>
            <span >Add Employee</span>
        </a>
    </li>
    <li>
        <a href="#2a" data-toggle="tab" data-index=3>
            <i class='bx bxs-group'></i>
            <span >Show Employee</span>
        </a>
    </li>
</ul>
</section>
<section id="content">
<main>
<div >
        <!-- dashboard -->
        <div  id="dashboard">

<!-- some code -->
</div>
 <div  id="1a">
<!-- some code -->
</div>
<div  id="2a">
<!-- some code -->
</div>
</main>
</section>

Javascript:

<script>
    $('#myTab a').click(function(e){
        e.preventDefault();
        $(this).tab('show');
        alert("h");
    });

    $("ul.side-menu > li a").on("shown.bs.tab",function (e) {
        var id = $(e.target).attr("href").substr(1);
        window.location.hash=id;
    });
    var hash = window.location.hash;
    $('#myTab a[href="'   hash   '"]').tab('show');
</script>

When I am refreshing the page this code is not working. This code is to keep active current tab active when the page is refreshed or page reload

CodePudding user response:

Simply add the currently active tab to localStorage. Do this by giving each tab a data attribute like data-index with a value like 1, 2, 3... Then you do localStorage.setItem("tabIndex", $(ul li.active).data(index);) which will save the data-index attribute of the active tab to the browser cache. You can then get the stored value after page load by using this var tabindex = localStorage.getItem("tabIndex");.

CodePudding user response:

this is my updated code but still is not working.

     $(document).ready(function(){
        $('a[data-toggle="tab"]').on('show.affectedDiv.tab', function(e) {
         localStorage.setItem("tabIndex", $(ul li.active).data(index));

        });
        var tabindex = localStorage.getItem("tabIndex");
        if(activeTab){
            $('#myTab a[href="'   activeTab   '"]').tab('show');
            alert("h");
        }
     });
  • Related