简体   繁体   中英

Stay on Tab after page reload

I'm using the following jquery for my tabs:

<SCRIPT>
    $.noConflict();
    jQuery( document ).ready(function( $ ) {
        jQuery('.tabs .tab-links a').on('click', function(e)  {
            var currentAttrValue = jQuery(this).attr('href');

            // Show/Hide Tabs
            jQuery('.tabs ' + currentAttrValue).show().siblings().hide();

            // Change/remove current tab to active
                  jQuery(this).parent('li').addClass('active').siblings().removeClass('active');

            e.preventDefault();
        });
    });
</SCRIPT>

And in the body:

<div class="tabs">
    <ul class="tab-links">
        <li class="active">
        <a href="#tab1">My Submissions</a></li>
        <li><a href="#tab2">History</a></li>
        <li><a href="#tab3">Messages</a></li>
    </ul>
    <div id="tab1" class="tab active">
        Info 1
    </div>
    <div id="tab2" class="tab">
        Info 2
    </div>
    <div id="tab3" class="tab">
        Info 3
    </div>
</div>

when I reload my page it resets to tab1 where as I want it to stay on the current tab I'm viewing for example tab2 or tab3

how would I accomplish this?

You can store current tab in localStorage.

<SCRIPT>
$.noConflict();
jQuery( document ).ready(function( $ ) {
if (window.localStorage){
    var currentTab = localStorage.getItem("currentTab");
    currentTab && $(".tabs .tab-links a[href='" + currentTab + "']").click();
}
jQuery('.tabs .tab-links a').on('click', function(e)  {
var currentAttrValue = jQuery(this).attr('href');
localStorage && localStorage.setItem("currentTab",currentAttrValue);
// Show/Hide Tabs
jQuery('.tabs ' + currentAttrValue).show().siblings().hide();

// Change/remove current tab to active
      jQuery(this).parent('li').addClass('active').siblings().removeClass('active');

e.preventDefault();
});
</script>

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