Search code examples
jqueryjquery-uijquery-ui-tabs

Keep active jQuery UI tab and related to it sub-tab after reloading page


I would like to keep active jQuery UI tab and related to it sub-tab after reloading page. Currently, I keep only tabs.

I use next script:

$(".tabs").tabs({
    active: localStorage.getItem("currentIdx"),
    activate: function (event, ui) {
    localStorage.setItem("currentIdx", $(this).tabs('option','active'));
               }});

https://codepen.io/evgenydym/pen/YvGRER


Solution

  • You can do it using storing value in sessionstorage:

    https://codepen.io/creativedev/pen/PaGerK

    $(document).ready(function () {
        var i = "0";
        var j ="0";
          $tab = $(".tabs").tabs({  
             activate : function (e, ui) {
                tabid = ui.newPanel.attr('id');
                if(tabid.indexOf("sub") != -1){
                  sessionStorage.setItem('sub-tab-index', ui.newPanel.attr('id'));
                }else{
                    sessionStorage.setItem('tab-index', ui.newPanel.attr('id'));
                }
             }
        });
    
        if (sessionStorage.getItem('tab-index') != null) {
            i = sessionStorage.getItem('tab-index');
            if(i !=''){
                $('.tabs li').each(function(){
                 var ac =  $(this).attr('aria-controls');
    
                 if(ac.indexOf("sub") == -1){
                    $(this).removeClass("ui-tabs-active ui-state-active");
                    console.log(ac)
                    console.log($('#'+ ac).css('display', 'none'));
                 }
               });
                $("#"+i).css('display','block');
                $('.tabs').find("[aria-controls='"+i+"']").find('a').trigger('click');
               $('.tabs').find("[aria-controls='"+i+"']").addClass('ui-tabs-active ui-state-active');
               //sessionStorage.removeItem('tab-index')
            }
        }
    
       if (sessionStorage.getItem('sub-tab-index') != null) {
             j = sessionStorage.getItem('sub-tab-index');
             if(j !=''){
                 $('.tabs li').each(function(){
                     var ac1 =  $(this).attr('aria-controls');
                     if(ac1.indexOf("sub") != -1){
                        $(this).removeClass("ui-tabs-active ui-state-active");
                     }
                   });
    
                $('.tabs').find("[aria-controls='"+j+"']").find('a').trigger('click');
                $('.tabs').find("[aria-controls='"+j+"']").addClass('ui-tabs-active ui-state-active');
              //  sessionStorage.removeItem('sub-tab-index');
             }
        }
    });