Search code examples
jquerycssjquery-mobile

jquery mobile: navbar not keeping active state


I have this navbar footer:

<div data-role="footer" data-position="fixed" data-theme="a" >
    <div data-role="navbar" data-iconpos="bottom">
        <ul>
            <li><a href="#page1" id="button_1" data-icon="user" class="my_buttons ui-btn-active">Page1</a></li>
            <li><a href="#page2" id="button_2" data-icon="lock" class="my_buttons">Page2</a></li>
            <li><a href="#page3" id="button_3" data-icon="camera" class="my_buttons">Page3</a></li>
            <li><a href="#page4" id="button_4" data-icon="comment" class="my_buttons">Page4</a></li>
            <li><a href="#page5" id="button_5" data-icon="check" class="my_buttons">Page5</a></li>
        </ul>
    </div><!-- /navbar -->
</div><!-- /footer -->

The problem is that the buttons don't keep their active state when clicked. This does work when a change a href to # on all buttons, but off course, this breaks my navigation.

I've tried adding ui-state-persist to all buttons, but that didn't work either. Anyone knows how to fix this?

Another thing I've tried is this:

$(".my_buttons").on( "tap", function() {
   var id = this.id;
   nav_state(id);
});

function nav_state(button)
{
   $(".my_buttons").removeClass("ui-btn-active",function() {
   $("#"+button).addClass("ui-btn-active"); });
}

This doesn't work either...

EDIT: Apparently, there's no callback for removeClass. Removing the callback didn't work either though...


Solution

  • You need to add your own code that updates the active button each time the page changes. There are different ways to do this, but here is one way:

    $(document).on( "pagecontainerchange", function() {
        var current = $( ".ui-page-active" ).prop("id");   
        // Remove active class from nav buttons
        $( "[data-role='navbar'] a.ui-btn-active" ).removeClass( "ui-btn-active" );
        // Add active class to current nav button
        $( "[data-role='navbar'] a" ).each(function() {
            var href = $( this ).prop("href");
            if ( href.indexOf(current, href.length - current.length) !== -1 ) {
                $( this ).addClass( "ui-btn-active" );
            }
        });
    });
    

    Each time the pagecontainer widget changes page, we get the ID of the page being shown and then step through the navbar links to see which href ends with this page id.

    DEMO

    You could also look at the persistent navbar demo which uses data-attributes: http://demos.jquerymobile.com/1.4.5/toolbar-fixed-persistent/