Tuesday 26 June 2012

JQuery Mobile and Cordova (phonegap) with multiple Html files


I was caught out with this one myself the other night and monitoring the phonegap google groups, its seems to be a source of confusion for a lot of people. Hopefully this will clear it up, tell your friends, developers, your pet dog and anyone else that may be interested.....

I didn't notice (even though it was emblazened in bold and flashed) that jquery mobile loads its subsequent pages via ajax which was the light bulb moment for myself on why the other pages wont work.  Ok, so i'm a bit slower than your average human.

What this means, is we have all our gubbins in the index html file and then subsequent pages only need the page div and markup in order to render.  Lets have an example (I assuming you have the standard cordova setup here with a www directory and all the pages underneath it)

here's our index.html file

<html>
     <head>
          <!-- include all your css here -->
     </head>

     <body>
          <div datarole="page" id="page1">
                <a href="page2.html">page2</a>
          </div>
     </body>

     //include cordova
     //include jquery
     //do your mobile init here in script if reqd.
     //include jquery mobile

     <script type="text/javascript">
       
          document.addEventListener("deviceready", onDeviceReady, false);
          function onDeviceReady() {
                 //cordova is ready here !
          }

          //jquery mobile
          //bind to the page 2's pageinit function to do stuff on page 2.
          $( '#page2' ).bind( 'pageinit',function(event){
         //do stuff for page 2 (you could put this in an include file)
     });
     </script>

</html>

page2.html

<div data-role="page" id="page2">
    my page 2 markup.
</div>

As we said previously, JQuery mobile will load the next page into the place where the page role is for index.html so, page1 in index.html is replaced with the contents of page2.  All the script code for page  2 goes in where we bind up.  I would eventually move this out into its own js file and include it in index.html.

hope that helps anyone with this issue out there !

1 comment:

  1. I hope you will continue to create such good articles. Effie

    ReplyDelete