Search code examples
jqueryjquery-mobilesettimeoutjquery-mobile-navbar

Tab active state in JQuery Mobile


Say we have 2 tabs using data-role="navbar", and we switch to the second tab and then go to another new page. When we return back from the previous page, why is the tab that we selected second tab is not the one which is active. It shows the first tab as only active. Is jquery mobile not handling this.


Solution

  • Description :

    Unfortunately jQuery Mobile don't handle this correctly so we need to do it. Basically you need to remove href from navbar li element. Page change will be handled manually. What we are doing here is binding a click event to navbar li element. When user clicks on navbar it will remove ui-btn-activ and ui-state-persist class from currently selected element. It will the add it to currently selected element and initialize a pageChange after a small timeout. Timeout is needed because we need to be sure class is added before page change can occur.

    Solution :

    Here's a working example I made some time ago: http://jsfiddle.net/Gajotres/6h7gn/

    Code:

    This code is made for my current example and its navbar so change it slightly to work with your navbar.

    $(document).on('pagebeforeshow', '#index', function(){ 
        $(document).on('click', '#kml li', function(){ 
            var selectedLi = $(this);
            $('#kml li').each(function( index ) {   
                var loopLi = $(this);
                if(loopLi.find('a').hasClass('ui-btn-active')) {  
                    $(this).find('a').removeClass('ui-btn-activ').removeClass('ui-state-persist');
                }
            });         
           selectedLi.find('a').addClass('ui-state-persist');        
           setTimeout(function(){
                $.mobile.changePage( "#second", { transition: "slide"});
            },100);
        });       
    });
    

    Edit :

    Next version example: http://jsfiddle.net/Gajotres/6h7gn/

    This one works on every page.

    $(document).on('pagebeforeshow', '#index', function(){ 
        $(document).off('click', '#custom-navbar li').on('click', '#custom-navbar li', function(e){ 
            var selectedLi = $(this);
            $('#custom-navbar li').each(function( index ) {   
                var loopLi = $(this);
                if(loopLi.find('a').hasClass('ui-btn-active') || loopLi.find('a').hasClass('ui-state-persist')) { 
                    loopLi.find('a').removeClass('ui-btn-activ').removeClass('ui-state-persist');
                }
                if(loopLi.attr('id') == selectedLi.attr('id')) {
                    loopLi.find('a').addClass('ui-state-persist');   
                }
            });              
           setTimeout(function(){
                $.mobile.changePage( selectedLi.find('a').attr('data-href'), { transition: "slide"});
            },100);
        });       
    });