Technology

Using jQuery mobile

Posted by Pixafy Team

Just recently I’ve had my first big experience working with jQuery mobile (jQM) for a client, and I want to share some of the basics that I learned along the way.  I’d worked with mobile sites before, but this takes mobile development a giant step forward.

The first thing everyone should know how to do before working with jQM is how to delegate events. This was the key to making a lot of things work.  Delegate is a jQuery function that (to summarize very briefly) allows events like clicks to be recorded even after AJAX calls.  jQM uses all AJAX to move between pages by default, so knowing how to delegate these events is key.

Here is an example:

$('body').delegate('#page', 'pageinit' ,function(){

    $('#page').delegate("#selector", 'click', function(e){...});

});

This code is finding the body tag.  The body tag should never be removed from the page with an AJAX call, so it’s like a constant anchor.  In this case we are delegating the pageinit event, which is a jQM custom event.  The delegated click event inside the pageint event should be used in place of the usual $(‘a’).click(); event.  This is because jQM will AJAX out the content within #page.

How do I know #page is going to have its content swapped out?  Because jQM allows us to determine what gets swapped out.  This is done with the custom attribute data-role=”page”.  I just threw on the ID of #page to make it easy to remember.

Here is an example:

body>

<div id="page" data-role="page">

                ...Content that will be swapped out with AJAX...

</div>

</body>

It is very important to use data-role=”page” as a wrapper around your entire HTML code, otherwise you make get some unexpected side effects.  Another reason to wrap all your code in page is to ensure all your custom jQuery events fire.

I find it works best like this:

<body>

<div id="page" data-role="page">

                <script type="text/javascript" src="js/scripts.js"></script>

                ...Content that will be swapped out with AJAX...

</div>

</body>

I encourage you to read about all the components and API and then play around with them yourself.  When you get going, it turns out to be a lot of fun to work with and is very useful.

Questions or comments? Share them below, or tweet us @Pixafy!