February 23, 2013

change pages in jquery mobile

In jquery Mobile, page navigation can be done by using $.mobile.changePage(). How it works? Actually, this method will programmatically change from one page to another page by using ajax load html instead of refreshing the whole page in browser.

Assume we have index.html and a page in sub directory pages/home.html.
Here is the example:

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, 
    user-scalable=no" /> 
  <title>Index page</title>
  <link rel="stylesheet" href="jquery.mobile-1.3.0.min.css" />
  <script src="jquery-1.8.2.min.js"></script>
  <script src="jquery.mobile-1.3.0.min.js"></script>
 </head>
 <body >
  <!-- Home -->
  <div data-role="page" id="indexPage">
   <div data-theme="a" data-role="header">
    <h3>
     I am index page
    </h3>
   </div>
   <div data-role="content">
    Content is here....
   </div>
  </div>
 </body>
</html>
Now, we would like to change page to page/home.html when the user start to navigate index.html. We bind a pagecreate event to "#indexPage" instead of "documenet". It is because bindind "pagecreate" event to document, the event will be fired every time changePage performed.

<script type="text/javascript >
 $("#indexPage").bind('pagecreate', function()
 {
  $.mobile.changePage("pages/home.html");
 });
</script>
After that you will see page/home.html is loaded.

Important notes:
If you are executing the html with file path in browser like this (file:///C:/test/index.html), $.mobile.changePage() cannot work normally because loading html, javascript by using ajax in local drive is not allowed. There is an alternative way to switch page instead of using $.mobile.changePage or put you files to hosting/ install apache/iis in your machine.

<script type="text/javascript >
 $("#indexPage").bind('pagecreate', function()
 {
   window.location = "pages/home.html;
 });
</script>

1 comment: