Adding Hash Change Events in Mobile Web Structure

Adding Hash Change Events in Mobile Web Structure

In a web browser when a user clicks a link, the page usually changes the URL schema. This happens when you navigate from to http:// However with most AJAX-driven mobile applications, you have only one physical page, but need a way to track navigation between virtual “pages.”

One way of doing this is through hash change events, which track when the hash (or the URL after the #  symbol) has changed. Whenever you click on a link, instead of redirecting to a physical page address, the hash is appended to the URL. The href attribute holds the hash ID of the page you want to link to. Each data-role page element must have an ID attribute that defines that page. For example, the Activity page is the page the user sees when the app is launched, which means the first <div class=”data-role”> element should have an ID of activity. This will help the jQuery Mobile handle the onHashChange  event.

To test this, create a page structure for the Manage tab. After the closing </div> from the main page, add this right below your <div id=”activity”> section:

<div  id=”manage” data-role=”page”>

<div data-role=”header”>


<div data-role=”navbar”  data-iconpos=”bottom”>


<li><a data-icon=”star”  href=”#activity”>Activity</a></li>

<li><a data-icon=”grid” class=”ui-btn-active”  href=”#manage”>Manage</a></li>

<li><a data-icon=”info”  href=”#find”>Find</a></li>

<li><a data-icon=”gear” href=”#settings”>Settings</a></li>

<li><a data-icon=”search”  href=”#search”>Search</a></li>


</div><!– /navbar –>

</div><!– /footer  –>

<div data-role=”content”>


</div><!– /content –>

<div data-role=”footer”>

<h4>Page  Footer</h4>

</div><!– /footer  –>


This keeps the header, but changes the active tab (using the ui-btn-active class) to Manage. After saving the page and launching the web page on your iOS emulator, the first page that loads is the Activity feed. After you tap the Manage tab at the top of the page, a quick fade-in and -out of the content occurs, and the Activity page is replaced by the Manage page. You can even use the back button to return to the Activity feed.

jQuery Mobile provides all the methods to help you get this running without much effort. When the document is loaded for the first time, the script looks for the element with the data-role of page. The first element on the page that matches this criteria is shown; the rest of it is hidden. Through inspection with any DOM section tool (such as Firebug or Webkit Inspector), you can see that jQuery Mobile by default sets the CSS property of display:  none and then applies the class of ui-page-active to the first element—in this case, activity. (See Figure 5-14.)

Adding Hash Change Events in Mobile Web Structure

 Figure 5-14:  The Web Inspector showing the ui-page-active  HTML

Written by imkits