New Kicks and Tricks: jQuery Mobile (book excerpt)

By Ricky Onsman

If you haven’t yet downloaded the free sample chapter of Earle Castledine and Craig Sharkie’s latest magnum opus for SitePoint, jQuery: Novice to Ninja, 2nd edition – New Kicks and Tricks, it’s high time you did. Or just cut straight to the chase and buy the book!

Why? Well, as someone who bought the first edition, I can vouch that there is plenty of new material in this edition, and the sample chapter is an excellent example.

Tell you what: let’s just take a look at it now. Here we go.

No exploration of advanced jQuery and jQuery plugins could be complete without a hat-tip to the newest kid on the block, jQuery Mobile.

Mobile moves jQuery away from the desktop and onto, well, “mobile” devices. Better yet, it builds on the lessons learned by both Core and UI, so even if you have only a passing understanding of those projects you’ll be ready to roll with Mobile. In fact one of the toughest things to come to terms with when you’re developing with Mobile is the extra steps it’ll take to view your handiwork in the target platforms.

No more ALT+TAB and refresh for Mobile developers—it’s now CTRL+S, pick up your phone or tablet PC, and hit reload.

jQuery Mobile blends the cross-browser and cross-platform support we know and love from jQuery with the power, flexibility, and design we turn to UI for—it’s a plugin, but not only does it extend  jQuery, it extends the places where you can rely on jQuery. You can select, bind, animate, and chain as you’d expect from a plugin, but you can also tap and swipe, use more CSS3 than ever before, and, most importantly, use your mastery of jQuery to make that next must-have application.

You’re able to focus on your application’s goal and let Mobile help you out without getting in the way—include two files, à la jQuery UI, and you’re away!

<link rel=stylesheet href="



<script src="


Looks familiar! Like you’re accustomed to, you can use jQuery’s own CDN to deliver your files as we’ve done here, or you can grab the files yourself and include them locally.

Using jQuery’s CDN, your minified and zipped files come in at 7kB and 24kB respectively—easily small enough to be useful on a mobile network. And you’ve got a host of platform options to access those mobile networks with. As it says on the jQuery Mobile website, “Mobile has broad support for the vast majority of all modern desktop, smartphone, tablet, and e-reader platforms.”

And this is no small claim: jQuery Mobile’s graded browser support matrix sees it catering to an impressive two dozen target platforms. This is not bad if you consider that some of the competitor products officially support only one.

Four Grades of Support

There are too many platforms for us to duplicate the full list of the graded support matrix, but you can find them all on the jQuery Mobile site.

Instead, let’s take a look at the coverage levels you can expect for each grade:

  • A-grade: full, enhanced experience with Ajax-based animated page transitions
  • B-grade: enhanced experience without Ajax navigation features
  • C-grade: basic, non-enhanced HTML experience that is still functional
  • Not Officially Supported: might work, but hasn’t been thoroughly tested or debugged

Mobile’s documentation is nearly as comprehensive as the support is. Each method and property is covered, and the documentation itself is written using Mobile —clever, huh? Arguably the documentation is easier to navigate on a smartphone than it is on the desktop!

As plugins go, jQuery Mobile is even more rich than jQuery UI—it has more features baked in, and more functionality that works as soon as you add the files to your application. And as Mobile is grounded in the HTML5 and CSS3 that are driving desktop development, it can even be enticing to non-mobile use cases.

Its support is still growing, and there are possibly some features that we’ll see added in later releases.

While Mobile doesn’t yet rate a mention in the navigation of jQuery Core or UI sites, there are myriad features to make applications that belie just how new the library is. Let’s take a look at some of those features.

Playing Your Trump

By now we know our client nearly as well as we know jQuery and jQuery UI, so it’s a safe bet for us that a mobile application with a social aspect is on the cards.

Let’s up the ante and deal with their next request by creating a mobile-based card game.

We’ll implement jQuery Mobile by making Pop Trumps: The Jemimas, the world’s first card game that combines the thrill of trumping your friends with the face of the newest rock star to hit the charts, as seen in Figure 4.1, Figure 4.2, and Figure 4.3.

The face of Pop Trumps
Figure 4.1. The face of Pop Trumps

Pop Trumps home page 
Figure 4.2. Our Pop Trumps home page

winners's screen 
Figure 4.3. The winner’s screen

Rather than go through every line of code, let’s focus on the Mobile-specific code where we can:

<link rel=stylesheet href="



<script src="


We have already looked at the Mobile requirement includes, but they are worth mentioning again. Unlike other jQuery projects, and in order to achieve the wide range of platform support, a great deal of manipulation occurs well before the document.ready event fires. As a result, we need to add our includes in the head of our document to achieve the best user experience.

While we’re in the document head, let’s look at that new meta element:

<meta name=viewport content="width=device-width, initial-scale=1,


jQuery Mobile draws heavily on HTML5, and here we have an HTML5 element that normalizes the cross-platform display of our application. It tells our browser that our content should be as wide as it  can be and that it should be at a 1:1 scale. This is important, given the wide range of resolutions our application may encounter.

That last content value—user-scalable=0—tells our browser not to make our content zoom. If zooming is something you’d like in your app, just omit that value and go with the browser’s default behavior.

Speaking of HTML5, let’s take a look now at our document structure. Again, if you have already worked with HTML5, there should be few surprises for you—except possibly how well Mobile embraces the language.

<section data-role="page" id="home">



<section data-role="page" id="albums">

<header data-role="header">



<div data-role="content">



<footer data-role="footer">




<section data-role="page" id="album">



<section data-role="page" id="results">



At its heart, our page is a group of section elements with a data-role attribute of page. You could also use div elements instead of sections—here, the attribute is more important than the element, as the data-role tells Mobile each of the sections will be a page in our application. We further delineate our pages with unique id attributes that serve as anchor targets for our navigation. Where a desktop might use ids to jump or scroll to content, Mobile uses them to transition between pageviews.

Inside our second section we’ve shown our basic pageview layout—a header, div, and footer, again all with data-role attributes that help Mobile apply its under-the-hood changes. Inside these  elements we just add whatever HTML we need and apply data-role attributes where it suits. Let’s try some now:

<a href="#albums" data-role="button">START</a>

Our first section with the id of home has an anchor which we tell Mobile we’d like to display as a button in our UI—we simply provide the data-role of button, and Mobile does the heavy lifting for us. Using the hash reference in our anchor is all we need do to load our next section, with an id of albums, into view.

In our albums section we continue using the simple HTML5 data attribute-driven approach. We tell our header to apply a theme using, you guessed it, data-theme.

We do the same for our unordered list, as well as telling it to be a data-listview, and the anchors in the list to have a data-transition of flip to control how our pages “turn”:

<header data-role="header" data-theme="b">

<h1>Pop Trumps</h1>


<div data-role="content">

<p>Select an album by The Jemimas to play</p>

<ul data-role="listview" data-inset="true" data-theme="b">

<li><a href="#album" data-transition="flip">

➥The Jemimas: Debut</a></li>

<li><a href="#album" data-transition="flip">

➥This is The Jemimas</a></li>

<li><a href="#album" data-transition="flip">

➥Awkward Third</a></li>

<li><a href="#album" data-transition="flip">

➥Best of The Jemimas</a></li>



Tapping the anchors in our attractively styled listview will now cause the album-designated page to “flip” into to view, which adds nicely to our card-like effect. You can also use slide, slideup, slidedown, pop, and fade; if you’re a fan of jQTouch,you might notice that these transitions have been ported from that library with only minor changes. After our flip we’ll have dealt one of our cards, and the players can get into some serious trumping. For us, though, the real interest lies in three new data-roles and a seamless DOM manipulation:

<div data-role="content">

<div data-role="fieldcontain">

<label for="flip-a" class="ui-hidden-accessible">

➥Select slider:</label>

<select name="slider" id="flip-a" data-role="slider"


<option value="no">☜ Number 1s</option>

<option value="yes">6</option>





<footer data-role="footer" data-theme="c">

<div data-role="controlgroup" data-type="horizontal">




The first new data-role is a fieldcontain, which does what you’d expect: contains fields. If you like, this data-role can be applied to a fieldset for some extra semantic sugar. The next is the slider role inside our fieldcontain, and the last is a controlgroup, which draws its name from an HTML5 hgroup and is used to group buttons.

The DOM manipulation triggered from a slider data-role shows Mobile’s roots in jQuery UI—the select element and its associated label are hidden in the interface and replaced by a sliding flip-toggle switch popular in mobile devices and illustrated in Figure 4.4.

Flip toggle
Figure 4.4. jQuery Mobile flip-toggle and grouped buttons

The controlgroup value has a no-less-striking effect in the interface, which it achieves using CSS alone (no DOM manipulation). By itself, the controlgroup value draws the links together and applies rounded corners to the first and last elements in the group. If you also add data-type=”horizontal” to the div containing the controlgroup value, as we’ve done in the preceding markup, the grouped buttons display in a row as you’d expect.

And our last data attribute is data-direction=”reverse”, which works with our transitions by reversing them. For example, where the default behavior is for a view to move in from the right of the screen, our data-direction attribute causes it to go out toward the right. When controlled, it provides the user with a strong sense of movement within the application. It doesn’t simply shift along an apparently endless series of views; rather, it moves around a series of pages like moving through chapters in a book:

<a href="#album" data-role="button" data-direction="reverse"


And speaking of moving through chapters, we’ve reached the point where we can start talking about writing our jQuery Mobile code. Well, almost.

Before we talk about the code we’ll write, we need to cover one more piece of code that runs without us doing anything: the mobileinit event. jQuery Mobile’s default transformations and styling are so good you’ll have little need to apply any changes, but for those rare times when they are required, you can leverage the mobileinit event—it allows you to extend or configure options as soon as the event fires.

This means you won’t need to overcome defaults—you can change settings before they’re applied, and there’s no need to wait for the DOM to load. So you won’t have to wait for $(document).ready() to take effect, nor document.loaded.

As a result, it’s recommended you reference your own local script files after referencing the jQuery library, as normal, and before referencing Mobile, like so:

<script src=""></script>

<script src="../path/to/your/scripts.js"></script>

<script src="


So we have sorted our semantic HTML, our source files are all in place, and the mobileinit event has fired. Let’s take a look at the code we’ve written to bring our game to life …

But that’s where we must leave our excerpt. As well as downloading this free sample chapter, you can also browse the Table of Contents and Index before you decide to buy jQuery: Novice to Ninja, 2nd edition – New Kicks and Tricks by Earle Castledine and Craig Sharkie.

  • Jim

    I’ve been experimenting with jQuery Mobile on a small intranet site, just to get used to it. As in the last example given, I linked to jQuery 1.7.1 and Mobile, and went to work. Everything looked great when I previewed in FF and Safari, but imagine my surprise when I previewed in IE8 (which IS supported), and saw a completely blank window!
    When I viewed the source on the jQuery Mobile “Docs” page, I noticed that it uses 1.6.4 instead of the latest version. I switched to that, and now IE8 displays fine. I realize that most people will probably be using Mobile to develop for, well, mobile sites, so this shouldn’t be too much of a problem. However, I never saw any warnings about it, so I thought I would give a heads-up to anyone doing anything similar.

  • Serg

    Hi Ricky,
    One of my choices was jQuery Mobile to develop mobile websites for this nonprofit organization.
    Most of the API features are self explanatory which it helps overcome the first stages. I’m working right now on a front end app to use a REST API service for the backend connection.
    By the way I have purchased the book (it’s awesome!) as much as all the sitepoint books.
    Will check back with you soon!


Get the latest in JavaScript, once a week, for free.