thinkbuildblog

Using jQuery mobile

Posted by Patrick Coleman

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:

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:

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:

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.

Categories: Tech topics Tags: , , , , , , Leave a comment
  • Tweet This
  • Like This
Patrick Coleman
About Patrick Coleman

Patrick is a Digital Interface Developer and joined Pixafy in August of 2011. In his time here he has proven to be a great utility player. He has focused much of his time here so far on JQuery, Javascript, AJAX and mobile solutions.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">