Last Updated: February 25, 2016
·
4.321K
· josephparente

Highlighting Active Navigation Item with jQuery Mobile

I had a difficult time finding a good example of highlighting the currently selected "page" in the navigation of a single-page jQuery Mobile app. Here is a combination of concepts from a variety of threads. There are likely more eloquent implementations, but this did the trick for my app.

I'm using a simple JavaScript include on each "page" to pull in the navigation from a single source:

var strFooter = '<div data-role="footer" data-position="fixed">';
strFooter = strFooter + '<div data-role="navbar" id="navbar">';
strFooter = strFooter + '<ul class="footerNav">';
strFooter = strFooter + '<li><a href="#page" class="ui-state-persist">Page</a></li>';
strFooter = strFooter + '</ul>';
strFooter = strFooter + '</div>';
strFooter = strFooter + '</div>';
document.write(strFooter);

Then using some simple jQuery to manipulate the elements:

$(document).ready(function() {
  $.mobile.changePage('#home');
  $('a').removeClass('ui-btn-active');
  $('[data-role=page]').live('pageshow', function() {
      if (window.location.hash != '')
      {
        $('#navbar a').removeClass('ui-btn-active');
        $('#navbar a[href="'+window.location.hash+'"]').addClass('ui-btn-active');
      }
  });
  $('.logo').live('vclick', function() {
    $('#navbar a').removeClass('ui-btn-active');
  });
});

The final result being that each time the "page" is changed, the active class is removed from the previously highlighted element, and based on the hash, the active class is then added to highlight the new selection.