How to stay on active tab after refresh on page?

1.1k views Asked by At

I’ve designed a tab page and followed the instruction from this post: http://alexchizhov.com/pwstabs/

How to stay on current tab when refresh page?

Here is my code:

jQuery(document).ready(function ($) {
   $('.tabset0').pwstabs();
   $('.tabset1').pwstabs({
      effect: 'scale',
      defaultTab: 3,
      containerWidth: '600px'
   });
   $('.tabset2').pwstabs({
      effect: 'slideleft',
      defaultTab: 2,
      containerWidth: '600px'
   });
   $('.tabset3').pwstabs({
      effect: 'slidetop',
      defaultTab: 3,
      containerWidth: '600px'
   });

});
<div class="content">
    <div class="tabset0">
        <div data-pws-tab="tab1" data-pws-tab-name="First Tab">
            First tab Content
        </div>
        <div data-pws-tab="tab2" data-pws-tab-name="Second Tab">
            Second tab Content
        </div>
        <div data-pws-tab="tab3" data-pws-tab-name="Third Tab">
            Third tab Content
        </div>
    </div>
</div>

I would appreciate if anyone can shed some light and help me with this.

2

There are 2 answers

0
BillyNate On

You could set a cookie when "opening" a tab, and on page load read the cookie and use PWS's defaultTab setting. Unfortunately PWS doesn't seem to dispatch events when changing tabs, so you will have to bind this to the "tab button".

Using js-cookie, reading the cookie could be something like this:

jQuery(document).ready(function ($) {
     var pwsTab3Settings = {
        effect: 'slidetop',
        defaultTab: 3,
        containerWidth: '600px'
     };

     if(Cookies.get('pwstab3')) {
       pwsTab3Settings.defaultTab = Cookies.get('pwstab3');
     }

     $('.tabset3').pwstabs(pwsTab3Settings);
  });
2
jony89 On

I would not do it with a cookie as the user might want to share this link,

instead i would add a hashtag to the url with the tabId or something,

E.g : http://alexchizhov.com/pwstabs#tabId and with javascript select the right tab after identifying selected tab . ( just like routing )

Though, if you have no interest in letting the user share the link maybe saving the data in localStorage / SessionStorage(for current tab only) / cookies might be the right solution for u

** Edit : **

To do the suggested solution above just add a js file to the whole pages which contain that tabs, lets call it tabRouting.js, the script could be as the following one ( wasn't tested though it will give you the idea ):

//url looking for : mydomain.com/#tab=tabId
(function($) {
    var hashString = window.location.href.split("#")[1];
    if(hashString)
    {           
        var tabId = hashString.replace(/tab=/, ""); 
        var tabItem = $("#" + tabId );
        $(tabItem).addClass("selected");
    }
})(jQuery)

This code must run after the tabs are rendered . Also notice that if you planning of doing some more use of the hashtag string this regex need to be enhanced.