jquery-mobile-develop-and-design_compress
jquery-mobile-develop-and-design_compress
But how do you build your development chops fast enough to join their ranks?
jQuery Mobile
With Peachpit’s Develop and Design series for visual learners.
jQuery Mobile
Develop and Design Develop and Design
jQuery Mobile
the jQuerY Mobile FraMeWork chanGes the WaY “Author Kris Hadlock covers the details of
mobile applications are accessed and distributed on mobile the framework with a practical, enjoyable
narrative that will quickly get you up to speed
and tablet devices. this game-changing JavaScript library takes and ready to create something great!”
existing webpages and converts them into touch-friendly web- Scott Jehl
sites and applications, eliminating the need for web developers Lead Developer of jQuery Mobile and Web Designer
and Developer with Filament Group
to create native applications for multiple mobile platforms.
Long-time developer and author Kris hadlock applies his real-
this book includes:
world, practical experience in this complete introduction to
creating working mobile sites using the jQuery mobile frame-
J easy step-by-step instruction, ample
illustrations, and clear examples
kris hadlock is the founder and lead developer-designer of Phoenix-based coMPanion Website:
web design and application development firm Studio Sedition (www.studio- http://peachpit.com/jquerymobile
sedition.com), and has worked with companies such as SPIN Magazine, IKEA,
United Airlines, and JP Morgan Chase. His other books include The ActionScript
facebook.com/peachpitCreativeLearning
Migration Guide and Ajax for Web Application Developers, and he has written for
hadlock
Peachpit.com, InformIT.com, IBM developerWorks, and .net magazine. @peachpit
Kris Hadlock
5 4 4 9 9
r
9 780321 820419
jQuery Mobile
Develop and Design
Kris Hadlock
jQuery Mobile: Develop and Design
Kris Hadlock
Peachpit Press
1249 Eighth Street
Berkeley, CA 94710
510/524-2178
510/524-2221 (fax)
Notice of Rights
All rights reserved. No part of this book may be reproduced or transmitted in any form by any means, elec-
tronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the pub-
lisher. For information on getting permission for reprints and excerpts, contact permissions@peachpit.com.
Notice of Liability
The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has
been taken in the preparation of the book, neither the author nor Peachpit Press shall have any liability to any
person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the
instructions contained in this book or by the computer software and hardware products described in it.
Trademarks
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and Peachpit was aware of a trademark claim, the
designations appear as requested by the owner of the trademark. All other product names and services identi-
fied throughout this book are used in editorial fashion only and for the benefit of such companies with no
intention of infringement of the trademark. No such use, or the use of any trade name, is intended to convey
endorsement or other affiliation with this book.
ISBN-13: 978-0-321-82041-9
ISBN-10: 0-321-82041-X
9 8 7 6 5 4 3 2 1
There are many people I would like to thank for the opportunity and help they gave
before, during, and after this book was being written: Neil Salkind, for helping me
navigate the world of publishing and for his support while I was writing. Robyn
Thomas for her patience. Jay Blanchard for stepping in when needed and provid-
ing excellent technical reviews. Rebecca Gulick for helping to move things along.
Michael Nolan for working out the details. All my customers, for understanding
how busy I’ve been. And, of course, Peachpit for giving me the opportunity to
write for you.
iv jQuery Mobile
contents
Contents v
Part ii ui CoMPonents
vi jQuery Mobile
Nested lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Inset lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Customizing Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Split button lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
List dividers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Count bubbles, thumbnails, and icons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Contents vii
Part iii the Mobile aPi
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
Contents ix
IntroducIng
the Future of
web development
Smartphone, tablet, and e-reader
statistics are showing an unprec-
edented adoption rate, making the
mobile web a very hot topic and requiring a new set of skills from
web developers and designers. Mobile device usage is skyrocketing;
according to Nielsen’s third-quarter 2011 Mobile Media Report, “44
percent of U.S. mobile subscribers now own a smartphone device,
compared to 18 percent just two years ago.” That’s more than double
in two years, and “the number of smartphone subscribers using the
mobile Internet has grown 45 percent since 2010.” As for tablets, in
June 2011 AMI-Partners (Access Markets International) forecasted
that “tablet adoption among businesses with between 1 and 1,000
employees will grow by 1,000 percent by 2015.”
xi
Let’s not forget e-readers, which are becoming very affordable and are more
advanced then ever, increasing in shipment volume, as “year-over-year growth was
167%” according to International Data Corporation (IDC). With the introduction
of the latest Kindle, mobile Internet access is now becoming a normal experience.
With these increases in adoption rate, there will no doubt be high demand for
web developers who can create rich mobile web experiences. The jQuery Mobile
framework gives web developers a quick and easy way to create mobile web experi-
ences, making the mobile web space hard to ignore.
IntroduCtIon xiii
Who thIs Book Is For
This book is for people who have basic HTML experience and are interested in
creating mobile websites using the jQuery Mobile framework.
WraPPing up
The jQuery Mobile framework is a powerful framework that is supported by mobile
industry leaders. It can easily be added to an existing website to create a mobile
web experience that is not only touch-friendly, but also supported on a majority of
the leading mobile platforms as well as handicap accessible. Design control, page
transitions, widget integration, scripting, API access, and much more are all at your
fingertips through this framework’s easy-to-use features and built-in progressive
enhancement techniques.
xvii
Currently, Android and Apple iOS are the leading mobile operating systems. Android
has the largest operating system market share (44.2 percent), while Apple has
the largest smartphone market share in the United States (28.6 percent). The
Windows, BlackBerry, SymbianOS, and Palm/HP webOS operating systems com-
prise the remaining majority of smartphone market share (Figure 1). All of these
platforms/operating systems are supported by the jQuery Mobile framework.
Major PlatForMs
The following list provides a bit more information on the major platforms that are
fully supported by the jQuery Mobile framework.
Nokia Samsung
Samsung 1.6% <1%
10.4% apple rIm BlackBerry
28.6% 17.0% hp
1.9%
motorola Samsung
10.7% <1%
other other
<1% <1%
other motorola
7.3% <1% other
<1%
% % %
1.6 2.0 7 1.3
%
%
.2
.6
.0
5.3
oS oS ne
17
44
28
ile
y
b
an e o
oS
oS
rr
ob
bi W ph
e
kB
d
ne
sm
m p s
oi
ac
ho
Sy / h dow
dr
w
Bl
ip
an
do
lm in
m
e
in
pl
pa W
rI
W
ap
graded suPPort
jQuery Mobile uses a three-tier, graded list of the
platforms that are supported by the framework. The
tiers are A, B, and C. A includes a full experience with
the option of Ajax-based page transitions, B includes
BlaCkBerrY WeBos the same experience minus the Ajax-based page
transitions, and C is a basic, yet functional, HTML
BlackBerry is powered weboS is the open-source
by a proprietary mobile operating system used by experience.
operating system, offered palm devices. weboS uses A-grade support includes all the major mobile oper-
on its own set of smart- the WebKit layout engine ating systems that were mentioned previously and
phones and tablets. in its web browser, simply more, including Apple iOS, Android, Windows Phone,
named Web.
BlackBerry, Palm/HP webOS, Kindle 3, Kindle Fire, and
more. B-grade support includes BlackBerry 5, Opera
Mini, and Nokia SymbianOS. C-grade support includes
BlackBerry 4, Windows Mobile, and all older smart-
phones and feature phones. This list is always evolving;
to see an up-to-date list, visit jquerymobile.com and
check out the supported platforms.
This page intentionally left blank
Part I
the
FoundAtIon of
jQuery mobIle
1
uNderStaNdING
jQuery
The jQuery framework is the
backbone of the jQuery Mobile
framework, so it’s helpful to know some
of the fundamentals of the jQuery framework before developing
jQuery Mobile websites. Although it’s not required, understanding
jQuery will make using jQuery Mobile even easier than it already
is, especially if you’re interested in writing any sort of custom
functionality.
5
getting stArted
To get started with jQuery, you first need to download the framework from
jquery.com and include it in your webpage, or you can simply reference it via the
Google, Microsoft, or jQuery content delivery network (CDN). I recommend and
most often reference the library via a CDN because it’s faster. A CDN will distrib-
ute your content across multiple, geographically dispersed servers, so the user
receives the closest available file. Plus, Google and Microsoft both offer versions
that support secure socket layers (SSL) via HTTPS, must-haves if you’re doing any
sort of development under SSL. To include the library via a CDN (we’ll use Google
as an example), use the script element to include it within the <head> elements or
at the end of your webpage.
<script type=”text/javascript”
src=”https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/
p jquery.min.js”>
</script>
Including JavaScript files within the <head> elements is the traditional approach.
However, according to Yahoo!, “80 percent of the end-user response time is on the
front-end.” Most of that time is spent downloading assets, such as style sheets,
images, scripts, and so on. It’s obviously important to reduce the number of assets,
but it’s also becoming more common to include JavaScript at the end of an HTML
file. This is because scripts block parallel downloads, meaning that other assets
will not download until each script is downloaded individually. To ensure that
you’re placing your scripts in the correct place, simply include them before the
closing </html> tag.
It’s also best to use the minified version in production environments, because it’s
smaller than the source version. In addition, although the packed version is smaller
than the minified version, it requires client-side processing time to decompress
the file and it’s not available in the most recent versions. According to Yahoo!, “In
a survey of ten top U.S. websites, minification achieved a 21 percent size reduction.”
y
jQuery FundAmentAls
If you’re familiar with writing JavaScript and CSS, then writing your first jQuery
script will feel very familiar, yet maybe slightly odd. The jQuery framework is a
JavaScript library, meaning that it’s built with JavaScript. The fundamentals are the
same, as you’re essentially still writing JavaScript, it just so happens that you’ll be
writing in a way that uses the jQuery framework. In other words, while there may
be added enhancements to certain fundamentals, the core of JavaScript—variables,
functions, conditional statements, and so on—has not changed. So, you’ll still be
using the var keyword, if and switch statements, and functions, but you’ll surely
notice a lot of additional enhancements and different ways of writing things, namely
accessing HTML elements.
jQuery offers many enhancements to the JavaScript language and, as mentioned,
the best part is that it’s cross-browser compatible, so you don’t have to worry about
writing multiple versions of the same script to handle different browsers anymore,
which is quite a relief. This is especially useful when working with events, Ajax
(discussed later in this chapter), and other functionality that traditionally requires
some conditional statements to determine how the browser will interpret the code.
J To access an element by ID using the jQuery selector, use the #id selector,
just as you would with CSS when attaching a class to an element by ID:
$(‘#foo’);
jQuerY Fundamentals 7
J To access an element by class name, use the .class selector, just as you
would when creating a CSS class. If you have multiple elements with the
same class name, they will all be selected.
$(‘.foo’);
J To target a specific element with a class name, add the element name before
the class name:
$(‘div.foo’);
J You can even target a specific element or set of elements using an element
selector:
$(‘div’);
If you’re familiar with CSS, you’re probably starting to see the pattern unfold and
the endless possibilities. The options available for structuring a CSS class are the
same ones you can use to access an HTML element with the jQuery selector. This is
how jQuery enhances JavaScript and CSS, taking the two and merging their syntax
into a new language that enhances the overall user experience, when properly
used, of course.
$(‘div.foo’).click(function(e) {
// Your custom code here
});
y
By binding the click event to the div, a function is associated with clicking the
mouse on that particular div. Therefore, anytime div.foo is clicked, your custom
code in the handler function will be executed.
If you’re familiar with traditional JavaScript, this syntax probably looks strange.
Don’t worry—it did to me as well when I first started using it, but once I caught on, I
liked it. Once you’re familiar with it, you’ll see that this code syntax is well contained,
easy to understand, and easy to write. Let’s break down the previous example:
1. The jQuery selector is used to select div.foo, which then becomes a jQuery
object.
2. The div.foo jQuery object then uses the click method to fire a handler
function when div.foo is clicked.
3. The handler function is used to execute the custom code. The handler also
has access to the eventObject, which is passed as an argument. In this
example, it is the e argument in the handler function.
If you use the jQuery selector to select a class name that’s being used by mul-
tiple HTML elements and assign a mouse event, that mouse event will be bound
to all of those elements automatically. Therefore, in the example above, if you had
multiple div elements with foo as the class name, the click event would be bound
to all of them. When working with events that are bound to multiple elements, it’s
important to consider scope to ensure that any custom code you’re executing is
applied to the desired element.
$(‘div.foo’).click(function(e) {
alert($(this).html());
});
note: scope is the enclosing context that values are associated with. in
this case, the function is the enclosing context and $(this) is the value.
jQuerY Fundamentals 9
$(this) is the same as using the this keyword in JavaScript; in this case, it
applies to the element that is currently firing the click event. When considering
scope, this always refers to the object associated with the enclosing context. In the
example, div.foo is the object and the handler function for the click event is the
enclosing context. jQuery will automatically assign the element that is clicked as
$(this) inside your anonymous handler function. This lets you access the element
that executed the event, even when the same code is applied to multiple elements.
Functions are used to execute a script or a set of scripts as the result of an event
or a simple and direct call to the function.
As you’ll learn later in this book, the bind method is often used by the jQuery
Mobile framework to handle custom events.
The custom events provided by jQuery Mobile create useful hooks for devel-
opment beyond the native functionality of the framework, meaning that you can
intercept certain existing events and add your own custom code. Such events
include touch, mouse, and window events, all of which you’ll learn how to extend
later in this book. The syntax for the bind method in jQuery is very similar to the
previous code example.
$(‘div.foo’).bind(‘click’, function(e) {
// Your custom code here
});
The difference is that you can react to multiple events with the same handler:
y
Or you can handle custom events, such as those implemented by the jQuery
Mobile framework:
Binding events will be covered in greater depth when we discuss how to bind
jQuery Mobile events with custom handler functions.
$(document).ready(function() {
// Your custom code here
});
First, you need to select the document object itself and then apply the ready
event. When the ready event fires, it will execute a function that will contain your
custom code. Continuing with the previous examples, you need to add the custom
code to the ready event to ensure that the document is ready before trying to apply
the click event:
jQuerY Fundamentals 11
$(document).ready(function() {
$(‘div.foo’).click(function() {
alert($(this).html());
});
});
Or you can use a shortcut version, which eliminates the need to access the
document and set the ready event.
$(function() {
$(‘div.foo’).click(function() {
alert($(this).html());
});
});
Using the ready event is the de facto standard with any jQuery development.
Not only does this approach ensure that your code will fire at the appropriate
time, it also lends itself to creating completely unobtrusive code, meaning that
you can write all your jQuery in a separate, external file that is simply referenced
from your HTML webpage.
$(document).ready(function() {
$(‘div.foo’).fadeIn();
});
y
Although these prebuilt animation methods appear to be independent, many
of them are powered internally by the animate method. The animate method can
be used to animate any numerical CSS property for an HTML element, such as
height, opacity, left, and right.
$(document).ready(function() {
$(‘div.foo’).click(function() {
$(this).animate(function(){
height: ‘+=50’
}, 1000, function() {
// Your custom code, when the animation is complete
});
});
});
Method desCriPtion
dequeue executes the next function in the queue for specified elements
jQuerY Fundamentals 13
The queue method provides a way to queue a string of sequential effects, mean-
ing that you can run multiple effects in a queue infinitely or you can stop the
queue by using the clearQueue method. The queue method is used primarily by
the FX (“effects”) queue, which is the default queue, but is also made available via
the jQuery API. This lets you queue any functionality that you need to happen
sequentially, not solely animations.
The queue and dequeue methods are meant to be associated with a particular
element or object. To use the queue method, you need to assign a queueName as
the argument, such as an anonymous function:
$(document).ready(function() {
$(‘div.foo’).fadeOut().queue(function(){
$(‘div.foo’).fadeIn();
next();
});
});
using ajax
Ajax is an acronym for asynchronous JavaScript and XML. Asynchronous means
that you can make a request to a server via Hypertext Transfer Protocol (HTTP) and
continue to process other data while waiting for the response. For example, you
can make calls to a server-side script to retrieve data from a database as XML, send
data to a server-side script to be stored in a database, or simply load an XML file to
populate pages of your website without refreshing the webpage. The functionality
available through the jQuery framework makes Ajax development much easier
than traditional JavaScript, by requiring less code and offering additional methods
and event handlers to cover any situation. The amount of jQuery code needed to
handle Ajax is minimal compared to traditional JavaScript, even when developing
complex functionality, which ultimately makes development much faster.
y
With traditional JavaScript, Ajax requires a lot of redundant code to form a
request and handle the response because of all the variations that are necessary
for the different browsers. To make a request and handle the response, you need
to write code similar to the following:
if(window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if(window.ActiveXObject) {
request = new ActiveXObject(‘MSXML2.XMLHTTP’);
}
request.onreadystatechange = onResponse;
request.open(‘GET’, ‘url for request’, true);
request.send(null);
function checkReadyState(obj) {
if(obj.readyState == 0) { // Sending Request }
if(obj.readyState == 1) { // Loading Response }
if(obj.readyState == 2) { // Response Loaded }
if(obj.readyState == 3) { // Response Ready }
if(obj.readyState == 4) {
if(obj.status == 200) {
return true;
}
else if(obj.status == 404) {
// File not found
}
else {
// There was a problem retrieving the XML
}
}
jQuerY Fundamentals 15
}
function onResponse() {
if(checkReadyState(request)) {
// Handle the response with one of the following properties
//alert(request.responseXML);
//alert(request.responseText);
}
}
jQuery.ajax({
url: ‘url for request’,
success: function(xml) {
// Parse the response
}
});
This code uses the jQuery object’s ajax method, includes a url property for
the request, and handles a success callback with an anonymous function. Many
more properties can be used within the jQuery object’s ajax method, such as the
type of request, either POST or GET (the default), a username and password, and
crossDomain. However, this example shows the ajax method in its most basic form
to illustrate the simplicity of jQuery Ajax calls.
Ajax is used in the jQuery Mobile framework to handle page changes and to
load or preload a page. The framework provides access through the application
programming interface (API) to handle this functionality, and we’ll cover it in-
depth later in this book.
y
WraPPing up
WraPPIng uP 17
2
the role of html5
As the starting point for all jQuery
Mobile development, HTML5
plays a key role in the jQuery Mobile
framework. HTML5 provides the gateway for everything from
defining how your webpage renders in mobile, tablet, or desktop
browsers to custom attributes that define widgets and themes and
much more. This chapter provides an overview of how HTML5
is used and what features are utilized most by the jQuery Mobile
framework.
19
semAntIc htMl5
Accessibility is a major focus and priority of the jQuery Mobile framework. This is
one reason why the framework is built on semantic HTML and why it’s available
to the widest possible range of devices. The techniques that the framework uses to
support A-grade browsers even provide access for users with screen readers such
as VoiceOver for Apple iPhone.
jQuery Mobile uses three levels to grade the support of the framework: A, B,
and C. A is full; B is full, minus Ajax; and C is basic support.
Standard, semantic HTML gives you the security of providing a mobile website
that is accessible to the greatest range of users without having to do the testing
yourself. This is the power of the jQuery Mobile framework.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
</body>
</html>
The <!DOCTYPE> declaration is supported by all major browsers. It’s also much
simpler to use than previous versions of HTML. HTML 4, for example, includes
three different versions of the <!DOCTYPE> declaration and requires the docu-
ment type definition (DTD) because it’s based on Standard Generalized Markup
Language (SGML).
The viewport meta tag was introduced by mobile Safari to let web developers
control the size and scale of the viewport. Many other major mobile browsers now
support this tag. It is used to set the browser’s layout viewport to improve the
presentation of webpages. Mobile web browsers obviously have a much smaller
screen size than desktop browsers and because of this they have a different layout
viewport association. If you’ve ever viewed a desktop website on a mobile phone
that isn’t using a viewport association that accommodates mobile devices, you’ve
most likely noticed that the site looks similar to Figure 2.1. Without the viewport
tag, your webpage can appear small, or zoomed out, as any other webpage not built
for mobile would display. The webpage can be very hard to read without
zooming in.
note: the iPhone screenshot used for Figure 2.1
was captured in Mobilizer, a mobile preview tool from
springbox (http://www.springbox.com/mobilizer/).
To include this tag in your HTML5 template, add it within the head element:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>Page Title</title>
</head>
<body>
</body>
</html>
The most important property to set is the width , which should be set to
device-width for mobile websites. The second property is initial-scale, which
defines the state of the website when it first loads, after which users can zoom in
or out. For example, if you were to set the initial-scale to 2, rather than 1, by
ProPerty desCriPtion
width Sets the width of the viewport in pixels. the value can be a specific
number in pixels; the default is 980. You can also use a dynamic
value, such as the width of the device (device-width). the device-
width value is commonly used in mobile development, because
it dynamically sets the width of the viewport to the width of the
device, and therefore accommodates all scenarios.
height Sets the height of the viewport in pixels. the value can be a specific
number in pixels.
initial-scale defines the scale of the website when it initially loads. the value
should be a number or decimal. the value is the multiplier by which
the initial scale is set.
minimum-scale defines the minimum scale of the website. the default is .25, and
the range is >0 to 10.
maximum-scale defines the maximum scale of the website. the default is 1.6, and
the range is >0 to 10.
user-scalable determines whether or not the user can zoom in and out to change
the scale of the viewport. a value of yes allows scaling, while a value
of no restricts scaling. a value of no also prevents a webpage from
scrolling when entering text into a form field.
HTML5 data- attributes let you store custom data that’s unseen by the user. In
other words, the data is not rendered or even used by the browser. With previous
versions of HTML, custom data is often stored in title, rel, class, or id attri-
butes, or in hidden HTML elements. The data stored in these attributes is acces-
sible to JavaScript. There are many reasons why access to custom data is useful
via JavaScript; it can be used behind the scenes to create custom functionality or
displayed to the user when a specific interaction occurs. A good example of using
custom data in a webpage is in an image gallery: A title and a description can be
added to an image and then used by JavaScript to display information about the
image that the user is viewing. The bottom line is that this is a misuse of these
HTML attributes, but until now it has been the only way to handle certain func-
tionality that is otherwise unsupported. Luckily, developers can start using HTML
attributes appropriately with the support of data- attributes.
Rather than having to use attributes with other predetermined uses, you can
now create custom data- attributes that are more relevant to your data and still
render valid HTML. The HTML5 specification supports any attribute that begins
with data- as a data storage area. Any name you want to append to the data- prefix
will be supported. For example, if you add custom data- attributes to an image
tag that belongs to an image gallery, you can add custom data-title and data-
description attributes and give them any custom value.
The attribute value can be any string, and as always, you need to escape any
double quotes within your strings.
Keep in mind the possibility of potential name clashing. As data- attributes
become more widespread, it’s likely that JavaScript libraries will be looking for
attributes with similar names, especially if generic attribute names are used, such
as data-description. A good solution to this problem is to use a custom namespace
within the name of the data- attribute. For example, if you’re developing a website
data-jquerymobiletv-foo
Not only does this prevent potential name clashing, it also personalizes the
code and makes it specific to your website or application.
The jQuery Mobile framework uses a number of custom data- attributes for
widgets and theming. These attributes are used during initialization and configura-
tion. Two common data- attributes are listed in Table 2.2.
data-role used to define any of the widgets in the jQuery mobile frame-
work. Setting this attribute within an html element lets you
add a widget to your webpage automatically.
Later in this book we’ll take an in-depth look at theming and using data-theme
attributes with jQuery Mobile. We’ll also cover more data- attributes associated
with the various widgets provided by the framework.
The framework itself allows you to define a custom namespace using a global
option in the configuration called ns (namespace). The ns option can be set to any
custom value, such as jquerymobiletv-. If you do use a custom namespace, it’s
best to use a dash at the end:
data-jquerymobiletv-foo
Otherwise, the result won’t include a dash between your namespace and the
custom data- value, so your data- attributes will be hard to read, and jQuery Mobile
will look for an attribute that looks like the following example:
data-jquerymobiletvfoo
data-role=”header”
To add this attribute to your HTML5 template you could simply add a div that
includes the attribute:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
</head>
<body>
<div data-role=”header”>
<h1>Header</h1>
</div>
</body>
</html>
data-jquerymobiletv-role=”header”
We’ll talk about configuration options, including the ns option, in more detail
later in the book.
With the introduction of data- attributes, developers have much more control
over the data that is added to a webpage. Custom attributes provide a means to
support semantic HTML while enhancing the webpage with front-end scripting
languages, such as JavaScript.
It may be daunting to think that you need to understand HTML5 and jQuery to
use the jQuery Mobile framework. Thankfully, the framework is built in a way
that supports developers with different skill levels. You don’t necessarily have to
know HTML5 and jQuery, because the framework provides a template for HTML5
that you can download directly from jquerymobile.com, and jQuery is available to
those developers who want to use it. The only thing that’s absolutely necessary is
to understand how to use data- attributes, because this is the way to add widgets
to a webpage without using jQuery.
WraPPIng uP 27
3
gettIng stArted
WIth jQuery
mobIle
In the previous chapters, we
covered basic jQuery, how to
create an HTML5 template, how
to add a viewport meta tag for mobile browsing, and how to use
data- attributes. Now you’re ready to dive into jQuery Mobile
and see how these languages, elements, and attributes are lever-
aged and enhanced using the framework. One of the great things
about the jQuery Mobile framework is that at its core it’s basic
HTML5 markup and JavaScript, which is supported by all major
browsers. For basic jQuery Mobile development, there honestly
isn’t that much to learn. This chapter covers the few steps and
provides a little background as to what’s happening behind the
scenes. In later chapters, you’ll see how you can expand on these
basic concepts to create more advanced jQuery Mobile websites
and even mobile web applications.
29
how jQuery Mobile works
There are many ways to build a jQuery Mobile website. However, in its simplest form,
the framework functions on top of HTML5 and the jQuery library to transform
elements with data- attributes into components, making it very easy to incorpo-
rate into your existing web development practices. The most basic components
of the framework are pages and toolbars, which will be explained in more detail
later in this chapter. But first, let’s look at how to incorporate the jQuery Mobile
framework into an HTML5 webpage.
note: keep in mind that at the time this book was written the latest
version of the jQuery Mobile framework was final version 1. to get the
latest code for including these files, visit jquerymobile.com, where you
can simply copy and paste it into your webpages.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>Page Title</title>
<link rel=”stylesheet” href=”http://code.jquery.com/
p mobile/1.0/jquery.mobile-1.0.min.css” />
<script src=”http://ajax.googleapis.com/ajax/libs/
p jquery/1.7.1/jquery.min.js”></script>
<script src=”http://code.jquery.com/mobile/1.0/
p jquery.mobile-1.0.min.js”></script>
</head>
<body>
</body>
</html>
The primary reason that content delivery network (CDN)-hosted files are rec-
ommended is because the load time is faster. A CDN will distribute your content
across multiple, geographically dispersed servers, so the user who is accessing
your webpage receives the closest available web files.
If you’re developing Microsoft .net applications, you can use the Microsoft
CDN-hosted jQuery Mobile files, which are currently available athttp://www.asp.
net/ajaxLibrary/CDNjQueryMobile10.ashx.
With the jQuery Mobile framework in place, you can begin to transform your
HTML5 markup into rich mobile components. Let’s take a look at the most com-
mon components: pages and toolbars.
<div data-role=”page”></div>
Voilà. I’m not sure if it can get any easier than this. jQuery Mobile will convert
this <div> element (most commonly used) into a page component. All you need
to do is use this markup and embed the framework in the <head> of your webpage.
Within the data-role=”page” element, you can use whatever HTML markup
you prefer. The most common elements to see within a data-role=”page” element
are <div> elements with data-role attribute values of header, content, and footer.
The header and footer data-role attributes are both considered toolbar compo-
nents in jQuery Mobile, while the content data-role is simply used to define the
content area of your website in which you can add any HTML markup. The follow-
ing example shows a typical HTML structure for a basic jQuery Mobile webpage
using these data-roles:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>Basic template - jQuery Mobile: Design and Develop
p </title>
<link rel=”stylesheet” href=”http://code.jquery.com/
p mobile/1.0/jquery.mobile-1.0.min.css” />
<script src=”http://ajax.googleapis.com/ajax/libs/
p jquery/1.7.1/jquery.min.js”></script>
<script src=”http://code.jquery.com/mobile/1.0/
p jquery.mobile-1.0.min.js”></script>
</head>
The code looks very similar to our previous examples, with the addition of the
page, header, content, and footer elements. The visual transformation of this
markup by jQuery Mobile can be seen in Figure 3.1.
The header, content, and footer are all transformed into a basic layout that
visually separates each of the sections. This is the default jQuery Mobile theme;
later in this book you’ll learn how to create custom themes. In this example, the
page title is displayed prominently at the top within the header, while the body
copy is formatted using the content data- attribute and the copyright is displayed
in a defined footer area.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>Page Title</title>
<link rel=”stylesheet” href=”http://code.jquery.com/
p mobile/1.0/jquery.mobile-1.0.min.css” />
<script src=”http://ajax.googleapis.com/ajax/libs/
p jquery/1.7.1/jquery.min.js”></script>
<script src=”http://code.jquery.com/mobile/1.0/
p jquery.mobile-1.0.min.js”></script>
</head>
<body>
<div data-role=”page” id=”page-one”>
<div data-role=”header”>
<h1>Page 1</h1>
</div>
This approach is not recommended, because files structured this way usu-
ally become harder to manage and are much larger in file size, so they ultimately
will take longer to load. For demos or prototypes, this may be an option, but it is
strongly recommended that you build your mobile websites or applications as
separate HTML files.
When using separate HTML files for your webpages, the page data-role is used
as a container that the framework loads other webpages into. For example, let’s say
you have two separate HTML files, page-1.html and page-2.html. Then you add the
page data-role attribute to both files and hyperlink page-1.html to page-2.html:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
With the jQuery Mobile framework included, the page data-role of page-1.html
will automatically become the container to load the markup within the page
data-role of page-2.html using an XMLHttpRequest. The XMLHttpRequest is
what Ajax uses to exchange data with the server without refreshing the webpage;
The HTML page itself is requested and jQuery Mobile uses its contents to display
the new page. There’s a lot to learn about this simple request, and we’ll cover it in
more detail in the coming chapters.
WraPPing up
Creating pages and including the jQuery Mobile framework is incredibly easy; the
depth of the framework shines through when we uncover the details that make
this framework so robust. As you’ve learned, data- attributes provide a way to
store custom data that is unseen by the user, but the data remains accessible to
JavaScript and, ultimately, to jQuery. This is why data- attributes play a large role
in jQuery Mobile. The framework uses these attributes to transform basic HTML
elements that use them as stylized widgets. We’ve only scratched the surface of
pages and toolbars, and there are still many other components to discuss. With
this basic information under your belt, it’s time to jump in and see what jQuery
Mobile has to offer.
WraPPIng uP 37
This page intentionally left blank
Part II
uI
components
4
creAtIng
multIpaGe
websItes
Now that we’ve covered the basics
of structuring mobile webpages,
we’ll take a deeper look and get a better
understanding of the functionality behind them. As mentioned
in Chapter 3, “Getting Started with jQuery Mobile,” there are two
ways to structure webpages for jQuery Mobile: incorporate all
the pages in the same file, or create separate files for each page
like a typical website. Understanding the different page template
types is the foundation for customizing a number of different
page-related functionalities. In addition to learning about the
page template types, you’ll also see how to preload and cache
pages, work with different page transitions, and customize load-
ing messages. You’ll learn to create custom functionality to take
your pages to the next level.
41
multIpAge teMPlate
Internal linking occurs automatically when you have multiple jQuery Mobile pages
in the same HTML file. As you’ve learned, jQuery Mobile pages are defined by add-
ing a data-role with a value of page to an HTML element and anything within that
page becomes relative to that page. In jQuery Mobile, typical separate webpages
are considered single-page templates, while webpages that contain multiple pages
are considered multipage templates. Let’s refer back to our multipage template
example from the previous chapter (with a few small additions):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>Multipage template - jQuery Mobile: Design and
p Develop</title>
<link rel=”stylesheet” href=”http://code.jquery.com/
p mobile/1.0.1/jquery.mobile-1.0.1.min.css” />
<script src=”http://ajax.googleapis.com/ajax/libs/
p jquery/1.7.1/jquery.min.js”></script>
<script src=”http://code.jquery.com/mobile/1.0.1/
p jquery.mobile-1.0.1.min.js”></script>
</script>
<script type=”text/javascript” src=”assets/js/ui.js”>
</script>
</head>
<body class=”container”>
<div data-role=”page” id=”page-one” data-title=”Page 1”>
<div data-role=”header”>
<h1>Page 1</h1>
</div>
Within this multipage template are two pages defined by div elements with
custom ids. The jQuery Mobile framework shows only one of these pages at a
time, and it uses the data-title attribute to change the page title dynamically.
The page that is shown by default is determined by the order of the source code.
In this example, the first page has an id of page-one, but if the pages in this file were
switched, so that the element with an id of page-two came first, then that would
be the default page to load. In other words, the value of the id attribute doesn’t
multIPage temPlate 43
figURe 4 .1 A multipage
template with two pages and
the transition in between.
determine what page is shown by default; the default page is determined only by
the source code order. However, the id is used for other important purposes, such
as linking pages to one another.
This is where jQuery Mobile pages begin to act like separate webpages. Note
that hyperlinks have been added to the original template to link from one page to
another. This is somewhat like the toggle functionality that’s common in JavaScript
development, where id values are used to hide and reveal certain HTML elements.
The difference here is that jQuery Mobile handles the functionality for you. To link
from one page to another you simply need to:
1. Create a hyperlink.
2. Type the pound sign (#).
3. Specify the id value of the page you want to link to.
The end result looks like this:
It’s similar to creating a page anchor; the difference is that you’re referencing
the id value of another page. Remember that each page needs a unique id value.
In this case, I’ve used page-one and page-two, but you can use something more
descriptive and relative to the content of your jQuery Mobile page. The cool thing
about the jQuery Mobile framework is that it transitions dynamically from one
page to another without requiring you to write an ounce of code. Figure 4.1 shows
an example of this code in both page views and the transition from one to another.
Single-page templates are separate HTML files that act as independent webpages,
just like any standard webpage. The main difference is in how jQuery Mobile con-
nects webpages using Ajax. As with multipage templates, the Ajax-based navigation
in single-page templates uses hashtags to create a page history. The Ajax-based
navigation used by jQuery Mobile is the default, but it can be turned off by setting
the ajaxEnabled setting to false in the configuration. You’ll learn more about the
configuration settings later in this book.
Ajah is an abbreviation that is sometimes used for Asynchronous JavaScript
and HTML. Ajah is essentially Ajax without the XML; the XMLHttpRequest is
still used, but HTML is exchanged with the server rather than XML. This is what
jQuery Mobile uses as the user browses independent webpages. We briefly covered
how the jQuery Mobile framework uses the XMLHttpRequest to load subsequent
pages in the previous chapter, but there’s a lot to learn and understand about this
simple request.
One great thing about the jQuery Mobile framework is how it tracks history:
it supports the back and forward buttons! Also, while subsequent pages load, the
framework provides a default loading message and transitions between pages. The
default page transition is to slide between two pages, and the default loading mes-
sage is a spinning icon with a “loading...” message. Both options are configurable,
as you’ll learn in the next chapter. For now, let’s see how hashtags and history
work in jQuery Mobile.
sIngle-Page temPlate 45
The only issue with jQuery Mobile’s hashtag-based navigation is that it doesn’t
support deep linking. However, there are some workarounds you can use to sup-
port this functionality. With a little help from jQuery, you can add a script, like the
following, to your webpage and your deep links will function as usual:
$(document).ready(function() {
$(‘a[href^=”#”]’).bind(‘click vclick’, function () {
location.hash = $(this).attr(‘href’);
return false;
});
});
In HTML, all hyperlinks that include a pound sign (#) as their first character
are identified as anchors. This script uses a regular expression that includes the
caret symbol to identify all anchor elements that have an href attribute with a
value that begins with the pound sign. Once these elements have been selected,
you can use the bind method to bind a click and vclick event to the anchor tags
and assign an anonymous function handler as the callback.
The callback function sets the window object’s location.hash to the value of
the anchor and returns false to prevent the browser from performing the default
action associated with clicking the hyperlink.
notes: the caret (^) symbol is often used in regular expressions to designate
the beginning of a string.
the vclick event is an option used in jQuery Mobile by devices that support
touch events. the event supports faster page changes and during page transi-
tions it keeps the address bar hidden.
jQuery Mobile supports standard HTML link types as well as a number of custom
link types related to the mobile experience. The following tables offer a list of
the supported link types available through the jQuery Mobile framework. Each
table shows options categorized based on their end result and/or support of Ajax.
Table 4.1 describes links that support Ajax.
p desCriPtion
<a href=”http://www.jquerymobile.tv”> a standard html link that is transformed by the jQuery mobile framework
p Hyperlink within same domain </a> to use ajax, include page transitions, and support page history.
<a href=”http://www.jquerymobile.tv” an option used for dialog windows that is not tracked in page history.
p data-rel=”dialog”> Open a dialog</a>
<a href=”http://www.jquerymobile.tv” this option can be used to navigate back in page history; it’s a great option
p data-rel=”back”>Back button</a> for providing a back button from a page or dialog. the href is ignored in
a- and B-grade browsers, but is necessary for C-grade browsers.
graded support
a-grade support includes all the major mobile operating systems men-
tioned previously and others, including apple ioS, android, Windows phone,
BlackBerry, palm WeboS, Kindle 3, and Kindle fire. B-grade support includes
BlackBerry 5, opera mini, and Nokia Symbian. C-grade support includes Black-
Berry 4, Windows mobile, and all older smartphones and feature phones. Visit
jquerymobile.com to see an up-to-date list of supported platforms.
lInk tYPes 47
Table 4.2 describes a list of hyperlinks that disable the Ajax page-transition
functionality. These hyperlinks are great for pages on an external domain, pages
that open in a new window, linking from single to multipage templates, or linking
to pages where you don’t want to use Ajax.
Table 4.3 includes link types that stem from a basic HTML hyperlink with the
addition of specific attributes.
p desCriPtion
<a href=”http://www.jquery.com” rel=”external”> By default this attribute defines a hyperlink as external, which not
p External hyperlink</a> only disables ajax, but also removes it from the page hashtag his-
tory and refreshes the webpage. this option can be transformed
using jQuery to open new windows in a standards-compliant way.
p desCriPtion
<a href=”tel:15556667777”>Phone Number</a> this hyperlink initiates a phone call when clicked on some phones.
<a href=”mailto:jdoe@jquerymobile.tv”> this hyperlink initiates a new email that’s prefilled with the
p Email link</a> specified email address.
<a href=”#”>Hyperlink</a> this hyperlink returns false. It’s useful when creating a back
button as in table 4.1.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>Single-page template - Page 1 - jQuery Mobile: Design
p and Develop</title>
<link rel=”stylesheet” href=”http://code.jquery.com/
p mobile/1.0.1/jquery.mobile-1.0.1.min.css” />
<script src=”http://ajax.googleapis.com/ajax/libs/
p jquery/1.7.1/jquery.min.js”></script>
<script src=”http://code.jquery.com/mobile/1.0.1/
p jquery.mobile-1.0.1.min.js”></script>
</script>
</head>
<body class=”container”>
<div data-role=”page”>
<div data-role=”header”>
<h1>Page 1</h1>
</div>
<div data-role=”content”>
<p><a href=”single-page-2.html”>Link to page 2</a></p>
<p><a href=”single-page-2.html” rel=”external”>
p External Link to page 2</a></p>
<p><a href=”single-page-2.html” data-ajax=”false”>
p Ajax-disabled link to page 2</a></p>
lInk tYPes 49
</div>
<div data-role=”footer”>
Copyright
</div>
</div>
</body>
</html>
An internal link requires no special markup and is where the framework will
interject and create a page transition between the current page and the page that’s
being linked to. An external link is one that requires the rel attribute, which must
be set to a value of external. Setting a hyperlink as external disables Ajax, removes
it from the page hashtag history, and refreshes the webpage when the link is clicked.
The link that disables Ajax requires a data-ajax attribute with a value of false.
This disables Ajax, removes it from the page hashtag history, and refreshes the
webpage, just like the previous example, with the main difference being that the
rel=”external” attribute can be used as a standards-compliant way to create
hyperlinks that target new windows with a little help from jQuery.
In this next example, there’s an internal link and a hyperlink that acts as a
back button:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>Single-page template - Page 2 - jQuery Mobile: Design
p and Develop</title>
<link rel=”stylesheet” href=”http://code.jquery.com/
p mobile/1.0.1/jquery.mobile-1.0.1.min.css” />
Setting the data-rel attribute to back creates a hyperlink that acts like a back
button. When this link is clicked, the jQuery Mobile framework automatically links
to the previous page in history.
lInk tYPes 51
preloAdIng and
cAchIng Pages
Page caching is very important when working with anything web-based. Cache
refers to hidden storage where files are collected. By default, browsers handle
webpage caching by putting the associated files in a local directory on the user’s
computer so the webpage and its associated assets will load more quickly during
subsequent visits. jQuery Mobile takes this concept a step further: the framework
allows pages to be cached even before they’re linked to or displayed in the browser.
Taking advantage of this functionality is as easy as using an HTML attribute named
data-prefetch. Simply add it to any hyperlink in your webpage, and once the
webpage has loaded, the URLs that these hyperlinks point to will be preloaded and
cached. The following line of code shows how to add this attribute to a hyperlink
to preload and cache the page it’s pointing to:
When running this example in a web browser, the request is made immediately
upon page load. Figure 4.2 shows an example of the XMLHttpRequest being made
from Chrome when the page loads.
The framework also provides a way to handle page preloading via the applica-
tion programming interface (API). We’ll talk more specifically about the API later
in the book, but it’s important to know how to access it.
$.mobile
Once the document object is ready, use the loadPage method to pass the URL
you want to preload and define a number of properties for the request:
$(document).ready(function() {
$.mobile.loadPage( “page2.html”, {
type: false,
reloadPage: false,
type: ‘get’
});
});
There are quite a few arguments you can pass as options in the loadPage method.
Table 4.4 lists those optional arguments.
arguMent desCriPtion
data holds an object or string that can be sent with an ajax page
request.
loadMsgDelay Sets the number of milliseconds to delay before showing the load
message. the default is 50 milliseconds.
pageContainer holds the loaded page. the default is the jQuery mobile page
container, but this is customizable.
reloadPage defines whether or not to reload the page being requested. the
default value is false.
role When the page is loaded, this defines the data-role value that will
be applied.
To cache a webpage using the API, you can set all pages to cache by default:
$.mobile.page.prototype.options.domCache = true;
Or, you can cache a page independently. You would cache a page with an id
of my-page like so:
$(‘#my-page’).page(true);
When working with the single-page template, jQuery Mobile also manages
the pages it preloads so the DOM doesn’t get too large. If many pages are kept in
the DOM, the browser’s memory usage can get out of control and the browser will
likely slow down or crash. To manage the memory size, the framework removes
pages that are loaded via Ajax from the DOM automatically via the pagehide event
when the visitor navigates away from them. You’ll learn more about this and other
events later in the book.
There are a number of benefits to preloading and caching pages. They load
quicker and prevent the Ajax loading message from appearing when a visitor tries
to access the preloaded page. However, it’s important to keep in mind that each
preloaded page creates an additional HTTP request, which uses more bandwidth.
Therefore, it’s important to preload pages only when you think visitors are likely
to view a subsequent webpage.
A number of page transitions can be used with the jQuery Mobile framework. All
the page transitions are CSS-based effects. When using Ajax navigation, the page
transitions work between linked pages or form submissions. Table 4.5 lists the
available page transitions in the framework.
Method desCriPtion
slide Slides the hyperlinked page in from the right to replace the current page. Slide is the default
page transition.
slidedown Slides the hyperlinked page down from the top to replace the current page.
pop Zooms the hyperlinked page in from the center of the current page and replaces it.
fade fades in the hyperlinked page over the current page and replaces it.
flip Creates a 3d effect where the hyperlinked page appears to be on the backside of the current
page as it flips and the hyperlinked page comes into view.
Each of these page transitions is easy to set up globally as a default using the
defaultPageTransition property. To set it up properly, it’s necessary to bind to the
mobileinit event, which is accessible through the API via the jQuery Mobile object:
$(document).bind(“mobileinit”, function() {
$.mobile.defaultPageTransition = ‘fade’;
});
The binding of the event handler needs to be executed before the jQuery Mobile
library loads. Therefore, in your HTML file, arrange your JavaScript files in a spe-
cific order:
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/
p jquery.min.js”></script>
<script src=”assets/js/custom-jqm-transitions.js”></script>
They can also be set on a per-link basis to override the default page transition.
This option is useful for a number of situations, such as creating pop-up windows
that use the pop transition:
It’s even possible to set the page transition to none to disable the page transi-
tion for a particular hyperlink or form submission:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
Beginning with the head of the document, you can see that the jQuery library
is loaded first, then the custom JavaScript where the mobileinit event from our
previous example is bound and the default page transition is set. Last, but not least,
the jQuery Mobile library is loaded. Within the page there’s a hyperlink that has a
pop transition applied and a form that has a flip transition applied.
When pages are loading, a default message appears if there’s a delay or if the page
is not yet preloaded. The jQuery Mobile framework allows you to customize this
message and a page-error loading message.
You can customize the loading message through the loadingMessage property.
Set loadingMessage to any custom string by binding to the mobileinit event, which
jQuery Mobile fires as soon as the document loads.
$(document).bind(“mobileinit”, function() {
$.mobile.loadingMessage = ‘Please wait’;
});
This code will display a loading message that says “Please wait.” The default
message used for page loading is “Loading.” The property can also be set to false
to display no message at all:
$(document).bind(“mobileinit”, function() {
$.mobile.loadingMessage = false;
});
When there is an error loading a page, jQuery Mobile displays a message that
can also be customized through the API. The default message for page-load errors
is “Error Loading Page.” You can set the pageLoadErrorMessage property to any
custom string as the error message:
$(document).bind(“mobileinit”, function() {
$.mobile.pageLoadErrorMessage = ‘There was an error, please try
p again.’;
});
Working with pages is easy with jQuery Mobile: all you really need to know is basic
HTML and a few mobile-related attributes. With most of the heavy lifting being
done by the framework, it’s easy to focus on the results of the website you’re build-
ing. Understanding the internal functionality behind how pages work in jQuery
Mobile is what begins to set you up for writing custom functionality. Customizing
specific functionality in the messaging and behind the scenes helps to personal-
ize your website. The level of customization that jQuery Mobile provides can be
very useful in making a website more user-friendly. Visual indicators, like custom
loading messages and page transitions, set expectations for visitors and provide
them with a frame of reference, so they know when certain things are happening.
Preloading and caching improves usability by speeding up page loads and giving
visitors what they want when they want it. jQuery Mobile provides fine-grained
control to enhance mobile websites in a custom way.
WraPPIng uP 59
5
dIAlog wIndows
aNd buttons
No mobile website or application is
complete without dialog windows,
pop-ups, and buttons to provide feed-
back and options to users. The jQuery Mobile framework lets you
create all of these with the addition of a simple data-rel attribute.
61
creAtIng a basiC
dIAlog wIndow
Creating a basic dialog window is easy with jQuery Mobile. Just use the data-rel
attribute on any anchor tag and set its value to dialog:
data-rel=”dialog”
Dialog windows can be included with a page or pages in a single HTML file
just like a multipage template, or they can be external webpages like a single-
page template. To create a multipage template that includes a dialog window, you
simply add another jQuery Mobile page—the difference is in how you link to it. In
other words, any page can be a dialog window; what makes it a dialog is the way
it’s opened. The following example shows a hyperlink with a data-rel attribute,
which opens a page in a dialog window:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>Dialog - jQuery Mobile: Design and Develop</title>
<link rel=”stylesheet” href=”http://code.jquery.com/
p mobile/1.0.1/jquery.mobile-1.0.1.min.css” />
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/
p jquery.min.js”></script>
<script src=”http://code.jquery.com/mobile/1.0.1/
p jquery.mobile-1.0.1.min.js”></script>
</head>
<body>
<div data-role=”page”>
<div data-role=”header”><h1>Dialog Test</h1></div>
<div data-role=”content”>
<p><a href=”#multipage-dialog” data-rel=
p ”dialog”>Open Multi-page Dialog</a></p>
</div>
<div data-role=”footer”>Copyright</div>
</div>
<div data-role=”page” id=”multipage-dialog”>
<div data-role=”header”><h1>Multi-page dialog window
p </h1></div>
<div data-role=”content”>
<p><a href=”dialog.html” data-rel=”back”>OK</a></p>
</div>
</div>
</body>
</html>
In this example, there are two pages: the first page is displayed by default. Within
this default page there’s a hyperlink that has a data-rel=”dialog” and a link to an
anchor. The anchor that’s being linked to is the ID of the second page. The second
page is set up like any jQuery Mobile page: it’s opened as a dialog because of the
way it’s linked to. Figure 5.1 shows the result of this code.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>Dialog - jQuery Mobile: Design and Develop</title>
<link rel=”stylesheet” href=”http://code.jquery.com/
p mobile/1.0.1/jquery.mobile-1.0.1.min.css” />
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/
p jquery.min.js”></script>
<script src=”http://code.jquery.com/mobile/1.0.1/
p jquery.mobile-1.0.1.min.js”></script>
</head>
<body>
<div data-role=”page”>
<div data-role=”header”><h1>Dialog Test</h1></div>
<div data-role=”content”>
<p><a href=”dialog-window.html” data-rel=”dialog”>
p Open External Dialog</a></p>
</div>
<div data-role=”footer”>Copyright</div>
</div>
</body>
</html>
The HTML file that’s being linked to can be set up like any jQuery Mobile
webpage:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8”>
<title>Dialog - jQuery Mobile: Design and Develop</title>
</head>
<body>
<div data-role=”page”>
<div data-role=”header”><h1>Single-page dialog window
p </h1></div>
<div data-role=”content”>
<p><a href=”#” data-rel=”back”>OK</a></p>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>Pop-up - jQuery Mobile: Design and Develop</title>
<link rel=”stylesheet” href=”http://code.jquery.com/
p mobile/1.0.1/jquery.mobile-1.0.1.min.css” />
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/
p jquery.min.js”></script>
<script src=”http://code.jquery.com/mobile/1.0.1/
p jquery.mobile-1.0.1.min.js”></script>
<style type=”text/css”>
.ui-dialog .ui-header,
.ui-dialog .ui-content,
.ui-dialog .ui-footer {
max-width: 640px;
}
</style>
</head>
<body>
<div data-role=”page”>
<div data-role=”header”><h1>Pop-up Test</h1></div>
<div data-role=”content”>
<p>President Barack Obama’s Inaugural Address</p>
<p><a href=”popup-window.html” data-rel=”dialog”>
p Play now ></a></p>
Dialog windows have a predefined width, but these can be overwritten via the
.ui-dialog classes. The HTML file in this example that’s being loaded as a pop-up
window includes a YouTube video of President Obama’s inaugural address. Since
the video is 640 x 360 pixels, the max-width has been set to 640. However, since
the width of a mobile device can be much smaller than 640 pixels, the width for the
video iFrame in the pop-up window has been set to 100%. This allows the video
to fill the width of the pop-up window regardless of the size, with a max-width of
640 pixels:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8”>
<title>Pop-up - jQuery Mobile: Design and Develop</title>
</head>
<body>
<div data-role=”page”>
<div data-role=”header”><h1>President Barack Obama’s
p Inaugural Address</h1></div>
<div data-role=”content”>
<iframe width=”100%” height=”360” src=”http://
p www.youtube.com/embed/3PuHGKnboNY” frameborder=”0”
p allowfullscreen></iframe>
</div>
</div>
</body>
</html>
By default, the dialog (or pop-up) window includes a Close button, so you don’t
need to add any other hyperlinks or functionality to the dialog window. Figure 5.3
shows an example of the video pop-up window with President Obama’s inaugural
address.
Dialog windows also include transitions. The default transition is pop, but this
transition can be changed to flip or slidedown. To change the transition, add the
data-transition attribute to the hyperlink that includes the data-rel=”dialog”
setting. If we were to add a slidedown data-transition to the previous example,
the code would look like this:
jQuery Mobile provides a way to create buttons with HTML anchor and input ele-
ments. Buttons offer a more usable alternative to standard hyperlinks and inputs
by creating a larger clickable area. To convert a hyperlink into a button, set the
data-role attribute to button (Figure 5.4):
By default, buttons are the full width of the containing element, but you can set
them to inline by using the data-inline attribute. This attribute, when set to true,
creates a button whose width is determined by the text in the hyperlink (Figure 5.5):
data-iconpos left | right | top | bottom | notext (left is the default value)
Input buttons differ from hyperlinks in that they all default to a button. The
following Submit button defaults to a jQuery Mobile button:
There’s nothing special about this input element. Figure 5.6 shows an example
of what this input button looks like when enhanced with jQuery Mobile.
Many types of input elements are auto-enhanced by jQuery Mobile as buttons.
These include input elements with a type attribute set to either button, submit,
reset, or image, all of which look the same by default. The only way to change
this default enhancement is to set the data-role to a value of none.
up arrow data-icon=”arrow-u”
delete data-icon=”delete”
plus data-icon=”plus”
minus data-icon=”minus”
Check data-icon=”check”
Gear data-icon=”gear”
refresh data-icon=”refresh”
forward data-icon=”forward”
Back data-icon=”back”
Grid data-icon=”grid”
Star data-icon=”star”
alert data-icon=”alert”
Info data-icon=”info”
home data-icon=”home”
Search data-icon=”search”
figURe 5 .8 A custom
checkmark icon.
J right
J top
J bottom
J notext (As seen in Figure 5.7, this value uses only the icon, hiding the text
within the hyperlink or input value.)
Custom icons can also be used via CSS. To create a custom icon, you first need
to choose a name value. For the purposes of this demo we’ll use checkmark. Using
this value in the data-icon attribute for a hyperlink or input that uses the button
plug-in generates a CSS class. The CSS class includes ui-icon- before the custom
value, so the CSS class for the custom value we defined is ui-icon-checkmark. With
this class in place, you can easily target the class and add a background image as
the icon:
.ui-icon-checkmark {
background-image: url(“5-custom-icon.png”);
}
When designing the icon, you’ll want to create an 18 x 18 pixel PNG-8 with
alpha transparency to match the built-in jQuery Mobile icons. Figure 5.8 shows
an example of the custom icon.
Now that we have created this icon and a CSS class associated with it, we can
assign the icon to a button. To assign our new icon to a button, we simply use the
data-icon attribute and set it to checkmark:
WraPPing up
The items in this chapter are the foundation of any mobile website or application.
Having the ability to provide feedback or ask for feedback from a user through
a dialog window is essential. Launching content in modal windows is the norm
these days, eliminating annoying pop-up windows. And buttons provide a way
to enhance any hyperlink or input button into a clickable, user-friendly solution.
WraPPIng uP 73
6
workIng WIth
toolbArs
The jQuery Mobile framework
offers toolbar widgets that let you
easily define headers and footers. As
with other widgets, toolbars are defined by data- attributes with
normal HTML markup and enhanced by the framework when
the webpage renders. Toolbars can contain navigation buttons
and be set in fixed positions at the top or bottom of your mobile
webpages. This chapter covers all the toolbar possibilities and
offers examples of each.
75
toolbArs
jQuery Mobile offers two types of toolbars: headers and footers. This section
covers both.
header toolbars
Header toolbars are the perfect way to provide a page title, navigation, or other
common calls to action, such as Save or Cancel buttons, in a web application. Header
toolbars are typically the first element in a mobile webpage. If a page title is used
in a header toolbar, any of the HTML heading-level elements can be used to con-
tain the title. Without a heading element, page titles contain no margin and are
not center-aligned as they are with heading elements; rather, they look like the
toolbar in Figure 6.1.
A heading element yields a result that looks much nicer than Figure 6.1. Heading
elements also allow for semantic webpages and flexibility in how elements are used.
The header element code we’ve been using thus far looks like the following example:
<div data-role=”header”>
figURe 6 .1 A header toolbar <h1>My Page Title</h1>
without a page title.
</div>
As you can see, the header is defined by a simple data-role attribute that has a
value of header. In this example, an h1 element has been added to define the page
title. Using this h1 element produces the results shown in Figure 6.2.
toolBars 77
adding buttons
With the button options discussed in Chapter 5, “Dialog Windows and Buttons,” and
an unlimited number of custom icons, you can address any functional requirements
you can imagine. Headers are a great location to prominently display important
buttons in a mobile web application, and it’s easy to do so using jQuery Mobile.
The following example shows how to add a Save button to a header element in a
dialog window to edit a user profile:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>Header Toolbar - jQuery Mobile: Design and Develop
p </title>
<link rel=”stylesheet” href=”http://code.jquery.com/
p mobile/1.0.1/jquery.mobile-1.0.1.min.css” />
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/
p jquery.min.js”></script>
<script src=”http://code.jquery.com/mobile/1.0.1/
p jquery.mobile-1.0.1.min.js”></script>
</head>
<body>
<div data-role=”page”>
<div data-role=”header”>
<h1>John Doe</h1>
<a href=”#options-dialog” data-icon=”gear” class=
p ”ui-btn-right” data-rel=”dialog”>Edit Profile</a>
</div>
<div data-role=”content”>
toolBars 79
Using the single-page template, a second page is added and a hyperlink is set to
open it as a dialog window from the default page. In the dialog window, the Save
button is visually represented by the appropriate data-icon attribute value. The
Option button in the default page uses a gear, and the Save button uses a check-
mark. Figure 6.4 illustrates a way to display an editable form in a dialog window
to modify a user profile. After updating the input values, the user can click the
Save button. You could put code in place to process the user’s updates and store
them in a database.
Buttons can also be grouped, rather than displayed individually. To group but-
tons, simply add a div as a container around them and apply a data-role with a
value of controlgroup with a data-type set to horizontal:
<div data-role=”header”>
<div data-role=”controlgroup” data-type=”horizontal”>
<a href=”#” data-role=”button” data-icon=”delete”>Delete</a>
You’ll also notice that there are data-role attributes set as button. This attribute
and value must be added to buttons within a controlgroup, otherwise the hyper-
links won’t render as buttons. Figure 6.5 shows that this example renders a toolbar
with a combined Delete and Save button, so the two no longer appear separate.
<div data-role=”header”>
<div data-role=”controlgroup” data-type=”horizontal”
p class=”align-left”>
<a href=”#” data-role=”button” data-icon=”home”>Home</a>
<a href=”#” data-role=”button”
p data-icon=”arrow-l”>Back</a>
</div>
<div data-role=”controlgroup” data-type=”horizontal”
p class=”align-right”>
<a href=”#” data-role=”button”
p data-icon=”delete”>Delete</a>
<a href=”#” data-role=”button” data-icon=”check”>Save</a>
figURe 6 .6 Multiple sets of
</div> grouped buttons.
</div>
These groups of buttons are also using custom classes that align one set left
and the other right. The CSS for these classes is a simple float left and a float right:
<style type=”text/css”>
.align-left {
float: left;
}
.align-right {
float: right;
}
</style>
Figure 6.6 shows these two groups of buttons and how they are separated in
a header toolbar.
toolBars 81
Footer toolbars
Footer toolbars are like header toolbars except that they typically reside at the bot-
tom, rather than the top, of a webpage. They are often used to display copyright
notices and other similar information.
<div data-role=”footer”>
<h4>Copyright</h4>
</div>
As with page titles in header toolbars, any text that’s added to the footer toolbar
needs a heading element to include spacing, alignment, and so on. The following
code example shows the markup for footer toolbars after it’s enhanced by the
framework:
Although footer toolbars are a good place for copyrights and the like, it’s also
possible to include all the same markup as a header toolbar, including buttons,
navbars, and so on.
<div data-role=”page”>
<div data-role=”header” data-position=”fixed”>
<h1>Page Title</h1>
</div>
<div data-role=”content”>
<p>Body Copy</p>
</div>
figURe 6 .7 Fixed toolbars.
<div data-role=”footer” data-position=”fixed”>
<h4>Copyright</h4>
</div>
</div>
toolBars 83
You can also update the position of toolbars via the jQuery Mobile API. Using
this method is sometimes necessary, for example, when a widget, such as an accor-
dion, is expanded and the page changes height. You can call the following code to
update the toolbar position:
$.mobile.fixedToolbars.show(true);
With regular fixed toolbars, the content sits between the header and the footer.
Fullscreen toolbars are common for video players or photo slideshows.
<div data-role=”header”>
<div data-role=”navbar”>
<ul>
<li><a href=”/”>Home</a></li>
<li><a href=”#”>About</a></li>
<li><a href=”#”>Contact</a></li>
</ul>
</div> figURe 6 .8 A navbar used in
a header toolbar.
</div>
Once again jQuery Mobile makes it incredibly easy to transform simple HTML
markup into a visually appealing and functional widget by adding a single attribute.
Figure 6.8 shows how this code renders visually.
The cool thing about the framework is that it evenly divides the space of the
navbar based on the number of buttons. This is why each of the buttons in Figure 6.8
is proportionate. The only caveat about navbars is that if they contain more than
five hyperlinks they’ll begin wrapping to multiple lines, as seen in Figure 6.9.
Although this is a limitation in one sense, it’s also a saving grace because mobile
devices simply don’t have the room to accommodate this many buttons in a hori-
zontal space.
<div data-role=”header”>
<img src=”assets/img/trademark-jquerymobiletv.png”>
<div data-role=”navbar”>
<ul>
<li><a href=”/”>Home</a></li>
<li><a href=”#”>About</a></li>
<li><a href=”#”>Contact</a></li>
</ul>
</div>
figURe 6 .10 A navbar and
a logo in a header. </div>
As shown in Figure 6.10, the logo is added above the navigation. Header toolbars
can include a number of elements; they’re not limited to buttons or page titles.
Figure 6.11 shows an example of a navbar that includes button icons.
This example shows what’s possible with the framework when you combine
widgets to create functionality.
Toolbars can help you create consistency in a mobile website by adding page titles
that have the same look and feel, navigation bars, or a combination of branding and
functional elements. In addition to look and feel, understanding how to leverage
headers and footers to create a more usable website is important and toolbars offer
the functionality needed to achieve this.
WraPPIng uP 87
ns
jQuery Mobile is flexible in the
sense that it’s based on standard
HTML and CSS, so the layout options
are essentially endless. However, the framework does offer a few
enhancements in the form of widgets you can use to organize
content and create custom layouts without writing additional code.
Using data- attributes and standard CSS classes, the framework
transforms the markup used to structure these widgets. In this
chapter, you’ll learn how to create grids, collapsible content, and
accordions.
89
grIds
Although jQuery Mobile still supports standard HTML tables, the framework also
offers a simple alternative in the form of a widget called grids. Grids let you position
elements next to one another. They’re useful for smaller elements such as buttons
and icons, but not recommended for large items or chunks of copy, since mobile
device resolution is much lower than the desktop environment and usability is
extremely diminished.
grid ColuMns
With jQuery Mobile, you can create up to a five-column grid using the four pre-
defined grid-column layout options shown in Table 7.1. Each column is based on an
individual CSS class with a naming convention that starts with the prefix ui-grid.
two-column ui-grid-a
three-column ui-grid-b
four-column ui-grid-c
five-column ui-grid-d
Creating a grid is easy once you determine how many columns you want: just
add the corresponding CSS class. The class for a two-column grid is ui-grid-a.
This will be added to a container element, in this case two div elements that act
as the two columns. Grid columns are defined HTML elements that include the
ui-block class prefix; the prefix is appended with a letter in alphabetical order
based on its position. For example, the first column’s CSS class is ui-block-a, the
second column’s class is ui-block-b, and so on:
<div class=”ui-grid-a”>
<div class=”ui-block-a”><strong>2-Column</strong></div>
<div class=”ui-block-b”>Column</div>
</div>
<div class=”ui-grid-a”>
<div class=”ui-block-a”><strong>2-Column</strong></div>
<div class=”ui-block-b”>Column</div>
</div>
<hr>
<div class=”ui-grid-b”>
<div class=”ui-block-a”><strong>3-Column</strong></div>
<div class=”ui-block-b”>Column</div> figURe 7 .1 A two-column grid.
<div class=”ui-block-c”>Column</div>
</div>
<hr>
<div class=”ui-grid-c”>
<div class=”ui-block-a”><strong>4-Column</strong></div>
<div class=”ui-block-b”>Column</div>
<div class=”ui-block-c”>Column</div>
<div class=”ui-block-d”>Column</div>
</div>
<hr>
grIds 91
<div class=”ui-grid-d”>
<div class=”ui-block-a”><strong>5-Column</strong></div>
<div class=”ui-block-b”>Column</div>
<div class=”ui-block-c”>Column</div>
<div class=”ui-block-d”>Column</div>
<div class=”ui-block-e”>Column</div>
</div>
<div class=”ui-grid-a”>
<div class=”ui-block-a”>
<div class=”ui-bar ui-bar-b”><strong>2-Column</strong></div>
</div>
<div class=”ui-block-b”>
<div class=”ui-bar ui-bar-b”>Column</div>
</div>
</div>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>Grids - jQuery Mobile: Design and Develop</title>
figURe 7 .3 A two-column grid
<link rel=”stylesheet” href=”http://code.jquery.com/ with the ui-bar class.
p mobile/1.0.1/jquery.mobile-1.0.1.min.css” />
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/
p jquery.min.js”></script>
<script src=”http://code.jquery.com/mobile/1.0.1/
p jquery.mobile-1.0.1.min.js”></script>
<style type=”text/css”>
.ui-grid-a div {
background-color: #ccc;
}
.ui-grid-a div.block-title {
background-color: #fff;
}
</style>
</head>
grIds 93
<body>
<div data-role=”page”>
<div data-role=”header” data-position=”fixed”>
<h1>My Page Title</h1>
</div>
<div data-role=”content”>
<div class=”ui-grid-a”>
<div class=”ui-block-a block-title”>2-Column</div>
<div class=”ui-block-b”>Column</div>
</div>
</div>
<div data-role=”footer” data-position=”fixed”>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>Grid with controlgroup - jQuery Mobile: Design and
p Develop</title>
<link rel=”stylesheet” href=”http://code.jquery.com/
p mobile/1.0.1/jquery.mobile-1.0.1.min.css” />
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/
p jquery.min.js”></script>
<script src=”http://code.jquery.com/mobile/1.0.1/
p jquery.mobile-1.0.1.min.js”></script>
<style type=”text/css”>
.ui-grid-a .ui-block-b {
text-align: right;
}
</style>
</head>
grIds 95
<body>
<div data-role=”page”>
<div data-role=”header”>
<div class=”ui-grid-a”>
<div class=”ui-block-a”>
<div data-role=”controlgroup”
p data-type=”horizontal”>
<a href=”#” data-role=”button”
p data-icon=”home”>Home</a>
<a href=”#” data-role=”button”
p data-icon=”arrow-l”>Back</a>
</div>
</div>
<div class=”ui-block-b”>
<div data-role=”controlgroup”
p data-type=”horizontal”>
<a href=”#” data-role=”button”
p data-icon=”delete”>Delete</a>
<a href=”#” data-role=”button”
p data-icon=”check”>Save</a>
</div>
</div>
</div>
</div>
<div data-role=”content”>
<p>Body Copy</p>
</div>
<div data-role=”footer” data-position=”fixed”>
<h4>Copyright</h4>
grid roWs
jQuery Mobile also lets you create grids with multiple rows. The same rules apply
as with the classes used for columns; however, rows are defined by each new set
of blocks that you add to a grid. For example, to create a four-column grid, the
ui-grid-c class must be used as usual. Inside the grid is where things get different:
simply repeat sets of block columns. In this case, it’ll be multiple block sets in a four-
column layout. The following example shows a four-column grid with two rows:
grIds 97
<div class=”ui-block-a”>
<div class=”ui-bar ui-bar-b”>A</div>
</div>
<div class=”ui-block-b”>
<div class=”ui-bar ui-bar-b”>B</div>
</div>
<div class=”ui-block-c”>
<div class=”ui-bar ui-bar-b”>C</div>
</div>
<div class=”ui-block-d”>
<div class=”ui-bar ui-bar-b”>D</div>
</div>
jQuery Mobile provides a widget that allows developers to create content that
can expand and contract. This widget, referred to as collapsible content, includes
a header and content area; the header acts as a button that can be touched to
expand and contract the content area. To create a collapsible content area, apply
the data-role attribute with a value of collapsible to a div that will be used to
contain a heading and content area. In the following example, the container element
with a data-role set to collapsible includes a heading and a paragraph element:
<div data-role=”collapsible”>
<h3>Collapsible content header</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
p Praesent non dolor quis elit suscipit commodo a eu velit.
p Nulla sodales velit arcu, at accumsan nisi. Donec porta
p tempus lorem, eget luctus diam luctus ac. Nunc et aliquam
p massa. Duis enim felis, varius quis pharetra quis, iaculis
p ac nulla. Morbi congue suscipit elit vel porta. Proin lacinia
p scelerisque risus, at elementum diam elementum et.</p>
</div>
CollaPsIBle Content 99
Collapsible content is a great way to organize large amounts of information.
Showing lots of data all at one time can be overwhelming and deter people from
accessing your valuable content. By hiding the content when the user first loads
a webpage, content can remain organized and users can reveal only the content
areas that they’re interested in.
Collapsible content areas can also include a data- attribute called data-
collapsed. By default, collapsible content areas are collapsed when the webpage
is first loaded. The data-collapsed attribute provides a way to expand collapsible
content areas when the page first loads. The following example shows the markup
to accomplish this:
<div data-role=”collapsible”>
<h3>Collapsible child #2</h3>
<p>Lorem ipsum dolor sit amet.</p>
</div>
</div>
The two highlighted collapsible content areas in this example are nested in
the main collapsible area. The result of this nested collapsible content will look
similar to Figure 7.8.
It’s also possible to nest deeper; in fact, you can nest as deep as you’d like.
Creating aCCordions
Collapsible content areas can also be grouped to create an accordion. An accordion
is essentially a group of collapsible content areas that are aware of one another.
For example, when one collapsible content area is expanded, any expanded ones
will close, so only one content area is expanded at a time.
To define an accordion, a container element must be created to contain a group
of collapsible content areas. On this container element, a data-role must be set
to the value collapsible-set. That’s it. The following code shows the markup for
an accordion with two collapsible content areas:
<div data-role=”collapsible-set”>
<div data-role=”collapsible”>
<h3>Header #1</h3>
<p>Lorem ipsum dolor sit amet.</p>
</div>
<div data-role=”collapsible”>
<h3>Header #2</h3>
<p>Lorem ipsum dolor sit amet.</p>
</div>
</div>
The code in this example creates an accordion that functions like the sequence
shown in Figure 7.9.
jQuery Mobile makes widgets incredibly easy to use, offering functionality that
would otherwise require custom JavaScript or jQuery. Using a simple data- attribute
or CSS class, the framework enhances these layout widgets and creates the required
functionality. Handling layout differences between devices is another benefit of this
framework: typically, CSS or JavaScript would need to be written to accommodate
the varying dimensions of different devices. With jQuery Mobile you can use any
custom HTML to create layouts, but it’s always beneficial to determine whether
the framework already includes a widget that can save you time.
WraPPIng uP 103
8
workIng
WIth lIsts
Lists are frequently used to display
data in jQuery Mobile. The frame-
work offers a plethora of formatting
options to achieve just about any design pattern you can imag-
ine, such as basic linked lists, numbered lists, nested lists, inset
lists, split button lists, and lists with dividers, as well as lists with
count bubbles, thumbnails, and icons. This chapter covers all
these design patterns, providing example code and figures to show
you how the end results should render.
105
bAsIc linked lIsts
One of the most common design patterns you’ll see with jQuery Mobile lists is
a basic linked list. Often used to display navigation, basic linked lists are simply
unordered lists that contain items with hyperlinks. jQuery Mobile enhances these
lists when a data-role with a value of listview is attached to the opening tag of
the unordered list element. The following markup shows how to create a basic
linked list using the listview data-role:
<ul data-role=”listview”>
<li><a href=”#”>Home</a></li>
<li><a href=”#”>Articles</a></li>
<li><a href=”#”>Videos</a></li>
<li><a href=”#”>Books</a></li>
<li><a href=”#”>More</a></li>
</ul>
As you can see, the framework makes a lot of additions to the code to produce
the visual enhancements. First, a ui-listview class is added to set the margin,
passing a list-style. Then the list items are updated with a data-theme attribute
set to the c theme, and a group of CSS classes is added. We’ll learn more about
jQuery Mobile themes later in the book. The classes that are added are ui-btn,
ui-btn-icon-right, ui-li-has-arrow, ui-li, and ui-btn-up-c. The names of
the classes basically explain it all; for example, the ui-btn adds a pointer cursor,
<ol data-role=”listview”>
<li><a href=”#”>Home</a></li>
<li><a href=”#”>Articles</a></li>
<li><a href=”#”>Videos</a></li>
<li><a href=”#”>Books</a></li>
<li><a href=”#”>More</a></li>
</ol>
The visual result looks similar to Figure 8.3, with the numbers inset as part
of the list item. figURe 8 .3 A basic numbered
list.
nested lists
Nested lists are hidden by default and load like additional pages. When a list is
nested within another list item, the parent list item becomes a hyperlink to the
child list and a new ui-page is generated for that list via the framework. To create
a nested list, simply take any list item and add another unordered or ordered list
to it. In the following example, the More list item from our previous examples is
configured as an h2 heading with a description and a nested unordered list:
<ul data-role=”listview”>
<li><a href=”#”>Home</a></li>
<li><a href=”#”>Articles</a></li>
<li><a href=”#”>Videos</a></li>
<li><a href=”#”>Books</a></li>
<li>
<h2>More</h2>
<p>Find more resources on jQuery Mobile</p>
<ul data-role=”listview”>
<li><a href=”http://www.jquerymobile.com”>
p jQuery Mobile</a></li>
<li><a href=”http://www.jquery.com”>jQuery</a></li>
</ul>
</li>
</ul>
When the framework enhances the listview, the More list item becomes a
hyperlink to the nested list, as seen in Figure 8.4.
The page generated from this nested list includes a header with the value of
the list item title and then the nested list itself. Lists can be nested as deeply as
you like; the framework will simply generate more and more pages.
Once you understand how to create basic lists, you may find yourself wanting more
options. Lists can be customized with dividers, thumbnails, icons, and more using
data- attributes. This section shows you what attributes can be used and how to
write the code for each of them.
The split button list in this example contains articles as list items that include
a title and an overview. When selected, additional details can be viewed for a
particular article. Each list item also includes a gear icon hyperlink that the user
can click to pay for access to the article within a dialog window. The visual repre-
sentation of this list is shown in Figure 8.6.
You can change the default icon for the split button that appears on the right
side of the list item by using the data-split-icon attribute. The icons available
with the data-split-icon attribute are the same as those available for buttons,
as seen in Figure 8.7, but you can also use custom icons.
<ul data-role=”listview”>
<li data-role=”list-divider”>The Beatles</li>
<li>Meet The Beatles!</li>
<li>A Hard Day’s Night</li>
<li>Help!</li>
<li>Rubber Soul</li>
<li>Revolver</li>
figURe 8 .8 A long list with
list dividers. <li data-role=”list-divider”>The Doors</li>
<li>The Doors</li>
<li>Strange Days</li>
<li>Waiting for the Sun</li>
<li>The Soft Parade</li>
<li>Morrison Hotel</li>
<li data-role=”list-divider”>The Jimi Hendrix Experience</li>
<li>Are You Experienced</li>
<li>Bold as Love</li>
<li>Electric Ladyland</li>
</ul>
The highlighted sections in this code example include a data-role with a value
of list-divider. Using the data-role attribute value of list-divider visually
differentiates these from other list items. Figure 8.8 shows how the list-divider
data-role creates this separation.
<ul data-role=”listview”>
<li>
<a href=”#inbox”>Inbox
<span class=”ui-li-count”>12</span>
</a>
</li>
<li>
<a href=”#outbox”>Outbox
figURe 8 .9 A simple list with
<span class=”ui-li-count”>0</span> count bubbles.
</a>
</li>
<li>
<a href=”#sent”>Sent
<span class=”ui-li-count”>57</span>
</a>
</li>
<li>
<a href=”#trash”>Trash
<span class=”ui-li-count”>1090</span>
</a>
</li>
</ul>
The end result of the code in this example is shown in Figure 8.9.
<ul data-role=”listview”>
<li>
<h2>The Beatles</h2>
<span class=”ui-li-count”>5</span>
<ul data-role=”listview”>
<li>Meet The Beatles!</li>
<li>A Hard Day’s Night</li>
<li>Help!</li>
<li>Rubber Soul</li>
<li>Revolver</li>
</ul>
</li>
<li>
<h2>The Doors</h2>
<span class=”ui-li-count”>5</span>
<ul data-role=”listview”>
<li>The Doors</li>
<li>Strange Days</li>
<li>Waiting for the Sun</li>
<li>The Soft Parade</li>
<li>Morrison Hotel</li>
</ul>
</li>
The result of this example is shown in Figure 8.10, with count bubble code and
nested lists all in the same list item.
You can add thumbnails just as you would add an image to an HTML page. Sim- figURe 8 .10 A simple list with
ply add an anchor element to a list item, add an image that will act as a thumbnail, count bubbles.
and add a title and the text you want to appear next to the icon:
<ul data-role=”listview”>
<li>
<a href=”#led-zeppelin/led-zeppelin-iv”>
<img src=”assets/img/led-zeppelin-IV.png” >
<h3>Led Zeppelin</h3>
<p>Led Zeppelin IV</p>
</a>
</li>
<li>
<a href=”#led-zeppelin/houses-of-the-holy”>
<img src=”assets/img/houses-of-the-holy.png” >
<h3>Led Zeppelin</h3>
<p>Houses of the Holy</p>
jQuery Mobile knows exactly how to handle lists that are set up this way, as it
converts the image into a thumbnail for the list items in the listview immediately.
The result of this code is shown in Figure 8.11.
Icons are added the same way as thumbnails; the only difference is that you
use the ui-li-icon class on the image element:
<ul data-role=”listview”>
<li>
<a href=”#led-zeppelin/led-zeppelin-iv”>
<img src=”assets/img/led-zeppelin-IV.png”
p class=”ui-li-icon” width=”16” height=”16”>
figURe 8 .11 A list with list
Led Zeppelin: Led Zeppelin IV
item thumbnails.
</a>
</li>
<li>
<a href=”#led-zeppelin/houses-of-the-holy”>
<img src=”assets/img/houses-of-the-holy.png”
p class=”ui-li-icon” width=”16” height=”16”>
Led Zeppelin: Houses of the Holy
</a>
</li>
</ul>
WraPPing up
Lists are of great importance to mobile websites and jQuery Mobile itself. As you’ve
seen in this chapter, the framework relies on lists to create navigation, organize
data, and much more. The level of customization is up to you; the options in this
chapter can be combined to create the ultimate list.
WraPPIng uP 119
9
SearCh FIlterIng
Basic search functionality is a com-
mon offering on websites these
days, but it can be time-consuming to
develop. Add to that a search that offers suggestions as the user
types, and the development time can double at least. Search sug-
gestions are becoming the norm and people often expect them.
Luckily, jQuery Mobile offers a solution: search filtering.
121
creAtIng a seArch Filter bAr
As mentioned, the jQuery Mobile framework makes adding a search filter bar to a list
incredibly easy: Just add the data-filter attribute to your list and set the value to
true. The following example is a truncated list of Beatles songs. Here the data-filter
is added to the unordered list element, but it can also be added to ordered lists:
As you can imagine, this list is incredibly long; however, the data-filter attri-
bute adds a search filter bar to the top of the list to help the user find what he’s
looking for. Figure 9.1 shows a sample of the sequence of events that happens
visually when the user types into the filter field. As letters are typed, the results
narrow, revealing only the items that match the search text.
As you can see, the framework adds a default value of “Filter items . . .” to the
search filter input field. You can change this default text with an additional attribute
named data-filter-placeholder, which can be used on the opening unordered
or ordered list element. The following example shows code that includes this
attribute on the previous list of Beatles songs:
The framework lets you change the search filter text through the API. To do
this, the listview component must be accessed after mobileinit event is triggered.
You’ll learn more about the jQuery Mobile API later in the book, but for now it’s
important to understand that the framework must be initialized before the API
can be accessed successfully. Once the listview is accessed, its options can be
altered. One such option is the filterPlaceholder property, which can be used
to update the search filter text. The following code shows a complete example of
how to write the code, including binding to the mobileinit event:
$(document).bind(“mobileinit”, function() {
$.mobile.listview.prototype.options.filterPlaceholder =
p “Search the song list...”;
});
Both of these options have the same visual result, allowing you to define any
text you want to appear in the search field. Figure 9.2 shows an example of how
the search filter looks with custom placeholder text.
Another nice feature of the search filter bar is that you can filter not only a basic
listview, but also a listview that includes custom formatting. A search filter on a
custom formatted list actually searches all the text within each list item, whether
it’s titles, paragraphs, or something else—you name it, the framework will filter
it. Figure 9.3 shows an example sequence of a custom formatted listview with
a search filter. The results include list items with a combination of matching text
from the paragraph copy and titles.
The jQuery Mobile framework gives you two options for creating custom search
filters. The listview includes a filterCallback option that can be extended
with a custom callback function. By extending this callback function, two argu-
ments—text and searchValue—become available and can be used to write custom
search criteria. The text argument is the value of the current list item, while the
searchValue is the value of the text that’s typed into the search filter. As a user
types into the search filter, the listview loops through the list comparing the list
item text and the search value, and filtering the results as necessary. Figure 9.4
shows an example of a console.log as jQuery Mobile compares the search value
and each list item’s text.
To customize the criteria, you can simply set a callback function using the
filterCallback property:
$.mobile.listview.prototype.options.filterCallback =
p myCustomCallback;
Or, you can access a specific listview by id and set the filterCallback prop-
erty for that listview only:
$(‘#my-listview’).listview(‘option’, ‘filterCallback’,
p myCustomCallback);
Let’s try adding a custom search filter to the Beatles song list using the listview
function. First, we’ll add a pageinit event to ensure that the page has loaded and
that it’s been enhanced by the framework. To do so we’ll need to add an id to the
page so we can target it with jQuery. The following example shows a page with an
id that can be targeted. A custom JavaScript file called filter.js is the file we’ll use
to create the callback function:
Once we have an id for the listview and have included a custom JavaScript
file, we can target the listview from within the JavaScript file. First, the docu-
ment must be ready. Once the document is ready, an event handler is created for
the pageinit method for the beatles-page element. When the page is initialized,
the listview code is executed, and the defaultSearch function is used as the
custom callback function:
$(document).ready(function() {
$(‘div#beatles-page’).on({
This example uses the default search criteria to log the text and searchValue
for testing purposes. Minus the console.log, this is the exact code that jQuery
Mobile uses to filter results as they’re entered into the search filter bar. First, the
text is converted to lowercase to make it a case-insensitive search, then JavaScript’s
native indexOf function looks for a string matching the searchValue in the text.
Now let’s take a look at how a custom callback function can be coded. This
time we’ll use the custom formatted listview from the earlier example and apply
a filter to it that searches only the body copy, excluding the list item titles from
the search criteria:
$(document).bind(“mobileinit”, function() {
$.mobile.listview.prototype.options.filterCallback = onlyBody;
});
function onlyBody( text, searchValue ) {
var splitText = text.trim().split(“\n”);
console.log(“text: “+ splitText[1]);
return splitText[1].toLowerCase().indexOf( searchValue ) === -1;
};
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,””);
}
WraPPing up
Search filter bars offer capabilities that would otherwise be rather complex and
time-consuming to program. jQuery Mobile makes it incredibly easy to add and
even customize this functionality. In addition to saving time, this widget provides
added value to any large amount of data and offers great usability enhancements,
helping users find what they’re looking for quickly and efficiently. Sometimes it’s
just not possible to pare down all the content that needs to go on a mobile website.
When this is the case and you have a very long list that seems nearly unusable, the
search filter bar is a great way to handle the problem.
WraPPIng uP 131
10
form elements
The jQuery Mobile framework
has exposed a number of internal
methods and events for each form ele-
ment, which means that you can access them from your custom
code. These methods and events let you alter and extend core
jQuery Mobile form element functionality to create customiza-
tions that set your mobile application apart from the rest. This
chapter covers each of the exposed form element methods and
events that are available to you.
133
text Inputs
jQuery Mobile supports many different text input types, including HTML5 inputs,
such as number, e-mail, URL, phone, and a few time- and date-related inputs.
The framework enhances all form elements to make them more usable on mobile
devices. One major advantage to identifying form elements with a specific ele-
ment type is that the keyboard changes. Following are some examples of the dif-
ferent text inputs and the associated iOS keyboards after they’ve been enhanced
by jQuery Mobile.
Setting an element type is done by adding an attribute named type and setting
its value to any of the values listed in this section. Here’s an example of a text input
with the type set to number:
When the element type is set to number, the input forces iOS to display a numeric
keyboard (Figure 10.1).
When the element type is set to number, but includes a pattern attribute of
0–9, the telephone pad appears (Figure 10.2).
When the element type is set to email, iOS includes an alphabetical keyboard
with an @ symbol and a period to help speed up input. If you have other mobile
devices, you can easily set up a form with these input types to see how each key-
figURe 10 .3 An alphabetical
board responds (Figure 10.3). keyboard with an @ symbol
and a period for e-mail
addresses.
jQuery mobIle 1.1.0
Just prior to publication of this book, a new version of the jQuery mobile
framework, version 1.1.0 final, was released. to benefit from some of the new
form element options, you must use the following code when including the
framework, CSS, and jQuery in your pages:
the jQuery mobile framework is constantly being upgraded. Check the down-
load page on jquerymobile.com before starting a project to ensure you have
the latest and greatest code.
A url element type reveals an alphabetical keyboard with a forward slash and
a .com key (Figure 10.4).
figURe 10 .5 A telephone A tel element type reveals a telephone keypad for phone numbers (Figure 10.5).
keypad for phone numbers.
The time, month, date, and datetime element types all reveal a menu that cor-
responds with the appropriate value (Figure 10.6).
$.mobile.textinput.prototype.options
Once you have access to the options, you can access each of them individually.
For example, if you want the initSelector option, you can append the option to
the end of the previous line of code:
$.mobile.textinput.prototype.options.initSelector
The initSelector option defines the selectors that are initialized when the
framework is initialized. The fact that this option is exposed is what lets you define
what selectors you want initialized as text inputs. This gives you great control over
core functionality, allowing you to define what is initialized based on your specific
situation, which ultimately minimizes initialization time. Not only can you define
what element types are initialized, you can do the same for data roles. The follow-
ing code leaves out all number element types as textinputs:
note: a number of different element types can be created with the textinput
element in jQuery Mobile, including text, search, number, password, email, url,
and tel. in addition to these, the textarea is grouped into the textinput form
element category in jQuery Mobile. this means that each element type includes
the options, methods, and events in the text input section of this chapter.
Figure 10.7 shows an example of the number element type without the
enhancements.
With the enhancements, the number element looks much nicer and is easier
for users to interact with in a mobile environment (Figure 10.8).
The textinput also includes a theme option, which you can access when select-
ing a text input element. The value of the theme can be set based on any prebuilt
or custom swatch that includes a–z:
$(‘.my-textinput’).textinput({theme: ‘a’});
This example accesses a text input element with a class name of .my-textinput
and sets the theme to a. You’ll learn more about themes in the next chapter.
As of version 1.1.0, jQuery Mobile also includes two new options: mini and
preventFocusZoom. These can also be set on an individual form element by using
the data- attribute named mini. Setting a form element to mini creates a more
compact version of it. To set a form element to mini with code, simply select the
text input(s), then use the textinput method to set the value of mini:
$(‘.my-textinput’).textinput({mini: true});
The result of this code on a text input looks similar to the right input in
Figure 10.9, which shows a comparison of the regular and mini text inputs.
The final option in the text input is the preventFocusZoom Boolean. When set to
true in iOS only, this option prevents the webpage from becoming zoomed in when
a user selects a text input. This is not the default: Usually iOS zooms the webpage
into the input, providing complete focus on the form element. This behavior is
often unnecessary, so luckily the jQuery Mobile team has provided an option for
disabling it. You can also set this option on an individual form element by using
the data- attribute named prevent-focus-zoom:
$(‘.my-textinput’).textinput({preventFocusZoom: true});
In addition to these options, the search input in particular has a specific option
called clearSearchButtonText that can be used to clear the search input text.
Simply set it as we’ve done with previous options:
Methods
jQuery Mobile exposes two simple methods for the textinput element: enable
and disable. The enable method activates the input and lets the user enter the
text input and type in it:
$(‘.my-textinput’).textinput(‘enable’);
When a text input is disabled, the user can’t interact with it:
$(‘.my-textinput’).textinput(‘disable’);
We’ve already seen an enabled text input in Figure 10.8; a disabled element
looks like Figure 10.10.
jQuery Mobile also adds custom events to some form elements. The text input
includes a create event as its custom event. The create event can be used to
execute custom code when a text input is created.
$(“.my-textinput”).textinput({
create: function(event, ui) {
console.log(‘my-textinput has been created’);
}
});
Checkboxes and radio buttons are similar in their options and markup. The main
difference is that you can select only a single radio button from a group. However,
you can select one, many, or all checkboxes in a group. Each element type has the
same layout options. For example, when you add a label and a checkbox or a label
and a radio button, you’ll receive the label and the element embedded in a button:
<div data-role=”fieldcontain”>
<fieldset data-role=”controlgroup”>
<legend>Pizza ingredients:</legend>
<label for=”cheese”>Cheese</label>
<input type=”checkbox” name=”pizza-ingredients” id=”cheese”
p value=”cheese” />
<label for=”mushroom”>Mushroom</label>
<input type=”checkbox” name=”pizza-ingredients”
p id=”mushroom” value=”mushroom” />
figURe 10 .12 A group of input
elements with a legend in a <label for=”pepperoni”>Pepperoni</label>
fieldset.
<input type=”checkbox” name=”pizza-ingredients”
p id=”pepperoni” value=”pepperoni” />
<label for=”green-pepper”>Green Pepper</label>
<input type=”checkbox” name=”pizza-ingredients”
p id=”green-pepper” value=”green-pepper” />
</fieldset>
</div>
The controlgroup data-role groups the buttons visually as shown in Figure 10.12.
<div data-role=”fieldcontain”>
<fieldset data-role=”controlgroup” data-type=”horizontal”>
<legend>Font styles:</legend>
<label for=”bold” class=”bold”>b</label>
<input type=”checkbox” name=”font-style” id=”bold”
p value=”bold” />
<label for=”italic” class=”italic”>i</label>
<input type=”checkbox” name=”font-style” id=”italic”
p value=”italic” />
<label for=”underline” class=”underline”>u</label>
<input type=”checkbox” name=”font-style” id=”underline”
p value=”underline” />
</fieldset>
</div>
This format provides button-like functionality that can be toggled, in this case
to turn font styles on and off. This code would not be complete without some CSS
formatting; in this case, the following CSS will be applied to the labels:
<style type=”text/css”>
.bold {
font-weight: bold;
}
.italic {
font-style: oblique;
}
.underline {
text-decoration: underline;
}
</style>
$(“input[type=’checkbox’], input[type=’radio’]”).checkboxradio({
mini: “true”,
theme: “e”
});
In terms of methods, checkboxes and radio buttons both have the standard
enable and disable methods. However, they also include a refresh method, which
you can use to update an element after visually manipulating it. For example, if we
took the pizza ingredients example and wanted to preselect cheese as an ingredient
choice, we could use the following code with a refresh:
$(“input#cheese”).attr(“checked”, true).checkboxradio(“refresh”);
This method ensures that the visual update is made to the checkbox, so the
user sees the checkbox as selected.
The checkbox and radio button elements include the same events as the text
input. These include the ability to bind standard JavaScript events, such as a change,
blur, focus event, and so on. These elements also have a create event that you
can use to execute custom code when they’re created in jQuery Mobile.
Select menus have been notoriously difficult to visually adjust. Finally, jQuery
Mobile has provided a visual look that makes sense with the framework and requires
no additional custom CSS coding. To create a select menu for jQuery Mobile, create
a regular HTML select menu. The following example shows a simple select menu
to choose a cabin type for a flight:
The result of this markup looks and functions like the example shown in
Figure 10.14.
As with checkboxes and radio buttons, you can add a bit of formatting. The fol-
lowing example includes a div with the fieldcontain data-role, which formats
the label and select menu slightly differently (Figure 10.15):
<div data-role=”fieldcontain”>
<label for=”select-cabin”>Cabin type:</label>
<select name=”select-cabin” id=”select-cabin”>
<option value=”economy”>Economy</option>
<option value=”business”>Business</option>
<option value=”first”>First class</option>
</select>
</div>
The result of this markup looks and functions like Figure 10.15.
<div data-role=”fieldcontain”>
<fieldset data-role=”controlgroup”>
<legend>Flight details:</legend>
<label for=”select-cabin”>Cabin type:</label>
<select name=”select-cabin” id=”select-cabin”>
<option>Cabin type</option>
<option value=”economy”>Economy</option>
<option value=”business”>Business</option>
<option value=”first”>First class</option>
</select>
<label for=”select-adults”>Adults</label>
<select name=”select-adults” id=”select-adults”>
<option>Adults</option>
<option value=”1”>1</option>
<option value=”2”>2</option>
<!-- etc. -->
</select>
<label for=”select-time”>Time</label>
oPtion desCriPtion
corners a Boolean used to apply the border-radius to the select button. the default is true.
icon a string that can be set to any of the built-in icons or a custom icon. the default is “arrow-down”.
iconpos a string used to set the position of an icon, if one is used. the default is “right”.
iconshadow a Boolean used to apply a shadow to the select button. the default is true.
initSelector a string that lets you change which elements are initialized by jQuery mobile. aside from the
actual select menu itself, the only other option is a data-role for the slider element.
inline a Boolean used to make the select button act like an inline button, which means that the width
is determined by the button’s text value. the default is false.
mini a Boolean that creates a more compact version of the select menu, just as it does other form
elements. the default is false.
nativeMenu a Boolean that can be set to determine whether the native menu for the device is used when
the select button is selected. the default for this option is true, as can be seen in the figures
that feature the select menu in ioS throughout this section.
overlayTheme a theme can be defined for the overlay layer of the select menu. the default is a.
preventFocusZoom a Boolean used to prevent or allow the device to zoom into the select menu when it is selected.
the default is true on ioS platforms.
shadow a Boolean that applies a shadow to the select button. the default is true.
theme a theme that can be associated with the select menu. this option’s default value is inherited
from its parent.
$(‘select’).selectmenu(‘open’);
Sliders are a great addition to the group of form elements that are available for
enhancement via jQuery Mobile. A slider can be used to choose a number within
a certain range as it sets that number in a corresponding number input. To create
a slider, you must set the element type to range and include a min and max value:
A default value can also be added, which sets the position of the handle on the
track. The slider in this example displays like Figure 10.18.
You can also add steps to the values that are returned. For example, if you didn’t
want to return every single number between 0 and 100, you could set the step
attribute to 10, which would return every tenth number:
In addition to these attributes, you can add a fill highlight, which highlights
the area of the track to the left of the handle (Figure 10.19):
oPtions
The slider element has a decent selection of options you can set via the API or as
data-role attributes, including disabled, highlight, initSelector, mini, theme,
and trackTheme. By default, the disabled option is set to false. The highlight
option defaults to false; however, it can be used to highlight the track to the left
of the handle on all sliders if set to true, as in the following example:
We’ve already covered the initSelector , mini , and theme options. The
trackTheme option is unique to the slider; you can use it to set the theme of the
track to a different theme than the rest of the slider.
slIders 153
Methods and eVents
The slider plug-in includes three methods you can use to modify a slider ele-
ment: enable, disable, and refresh. The enable method enables a disabled slider:
$(‘.selector’).slider(‘enable’);
The disable method disables a slider so the user can’t interact with it:
$(‘.selector’).slider(‘disable’);
The refresh method can be used to refresh a slider after it’s been updated
visually or functionally via JavaScript:
$(‘.selector’).slider(‘refresh’);
The events available to the slider plug-in are similar to those for other form
elements. They include the ability to be bound to any standard JavaScript event,
such as change, focus, blur, and so on. The slider plug-in also includes a create
event you can use to execute custom code when the slider is created.
The code that produces this toggle switch is a select menu with a data-role
set to a value of slider and, of course, the key is to include only two options. The
visual result of this slider is shown in Figure 10.20.
The flip toggle switch includes the exact same options, methods, and events as
the slider, and each is accessed with the same syntax since the flip toggle switch is
essentially just an extension of the slider. To learn more about the options, meth-
ods, and events accessible to the flip toggle switch, check out the “Sliders” section
earlier in this chapter.
WraPPing up
jQuery Mobile offers great element options for handling form input. Usability
increases dramatically with devices that respond with the appropriate keyboard
based on the input type. Another bonus is that all of these form elements degrade
when viewed in a browser that can’t handle them, so you never need to worry about
your webpage breaking because someone isn’t using the latest and greatest mobile
phone, for example. This is just another way that jQuery Mobile helps eliminate
some of the common frustrations that come along with web development in general.
WraPPIng uP 155
11
themIng
jQuerY moBIle
jQuery Mobile includes a complete
theme framework that lets you
customize color swatches and icon sets
to create custom themed pages, toolbars, content, form elements,
lists, buttons, and more. The framework uses CSS3 for many of its
enhancements, such as shadows, gradients, and rounded corners,
so no images are used to make these visual aspects, which makes
the theme more lightweight and quick loading.
157
core Color swAtches
jQuery Mobile has a theme system containing five swatches that are defined by the
letters “a” through “e.” Swatches can be mixed and matched throughout a single
webpage to allow for complete customization. The default swatches all contain
color and texture, padding, and predefined dimensions to separate them from
one another. Table 11.1 includes the default swatches and descriptions of each.
a Black highest
b Blue Secondary
c Gray Baseline
e Yellow accent
figURe 11 .1 Group of buttons Using a swatch is as simple as using the data-theme attribute, which can be
with different theme swatches used on any HTML element with the jQuery Mobile framework. The following code
assigned.
shows a group of five buttons, each with a different default theme:
Whether this is a set of buttons, list items, or bars, the jQuery Mobile framework
gives you the ability to define different themes for these items. Figure 11.1 shows
the group of buttons in the example. As you can see, each has a different color
based on the theme assigned to it.
You can update an existing swatch or create a custom color swatch. To create
a custom swatch, simply copy an existing theme swatch from the jQuery Mobile
style sheet and update it to a letter that’s not already in use as a default swatch
(that is, letters “f ” through “z” or any custom name). First, you’ll need to find a
swatch in the style sheet that you want to copy; let’s use the “a” swatch for this
.ui-bar-f {
border: 1px solid #cccccc;
background: #cccccc;
color: #cccccc;
font-weight: bold;
text-shadow: 0 -1px 1px #000000;
background-image: -webkit-gradient(linear, left top,
p left bottom, from(#cccccc), to(#999));
background-image: -webkit-linear-gradient(#cccccc, #999);
background-image: -moz-linear-gradient(#cccccc, #999);
background-image: -ms-linear-gradient(#cccccc, #999);
background-image: -o-linear-gradient(#cccccc, #999);
background-image: linear-gradient(#cccccc, #999);
}
Now it’s up to you to customize the properties of those classes. Once you have
your new swatch, you can easily use it on any jQuery Mobile element, as in the
following button example:
Another way to create a custom swatch is to use the ThemeRoller tool, which lets
you create an entire theme with multiple custom swatches in a simple interface.
tip: the themeroller tool is an easy way to create a custom theme, but the
tougher route can give you a better understanding of the inner workings of the
Css classes that are applied when the jQuery mobile framework enhances your markup.
even if you ultimately use the themeroller tool, it’s a good idea to check out the existing
classes to see what’s happening behind the scenes.
Each component handles theme swatches in its own way. This section provides an
overview of how each component handles swatches and gives you a visual reference.
Figure 11.4 shows the result of this modified markup with the data-theme.
Like pages, any components included in the toolbar inherit the toolbar’s theme.
The following example shows a header with a button that has a different theme
and the home icon:
This markup creates a button that stands out against the toolbar theme
(Figure 11.5).
Notice how the page uses the “b” swatch, while the content area uses the “d”
swatch. Figure 11.6 shows how the content component and its components over-
ride the inherited page component theme.
By default, the header of the collapsible content area includes the custom
data-theme; but without the data-content-theme, the body of the collapsible
content area remains the same theme as the containing content area. Figure 11.7
shows an example of the collapsible content area with a custom data-theme and
data-content-theme, so that both match.
This sets the button to a different theme from the rest of the form. In this
case, it helps identify the button within the form, drawing attention to it visually
(Figure 11.9).
list
Lists are probably the most complex component in jQuery Mobile, because they’re
the only element that includes additional attributes for theme options. For example,
the listview can contain not only list items, but also dividers, count bubbles, and
split buttons, all of which have their own theme options, as we’ll see in this section.
First, like the previous components discussed in this chapter, the listview itself
figURe 11 .9 Setting an indi- can contain a data-theme, which will be inherited by any of its contained items:
vidual form element’s swatch
value using the data-theme <div data-role=”page” data-theme=”b”>
attribute.
<div data-role=”header” data-theme=”b”>
<h1>jQueryMobile.tv</h1>
<a href=”#” data-theme=”e” data-icon=”home”>Home</a>
</div>
<div data-role=”content” data-theme=”d”>
<p>This content area includes the “d” swatch.</p>
<ul data-role=”listview” data-inset=”true” data-theme=”e”>
<li><a href=”#”>List item</a></li>
<li><a href=”#”>List item</a></li>
Figure 11.10 shows an example of how this markup renders on a mobile device.
As you can see, the list can have its own theme, separate from the rest of the page.
However, if no data-theme is defined, the listview simply inherits the theme
from the page or its content container.
It’s also possible for individual list items to override the listview theme. If
it makes sense for a specific list item to stand apart from the others, simply add
a data-theme attribute to it:
Figure 11.11 shows an example of this listview that includes the “e” swatch
as its data-theme and a list item that overrides that theme with the “a” swatch. In
this particular case, this functionality is helpful, because it highlights and draws
attention to a specific list item.
Figure 11.12 shows this code in action with the listview using the
data-divider-theme attribute for its dividers.
Count bubbles can be themed with the data-count-theme attribute, which can
be applied to the listview ul element to theme all count bubbles within the list:
Split buttons let you set two separate links in the same list item. To create
a separate theme for these split buttons, you can add the data-split-theme attri-
bute to the listview ul element:
jQuery Mobile themes are easy to use and powerful at the same time. Every compo-
nent can be themed, and when prebuilt swatches are not enough, you can always go
custom. Between the ThemeRoller and the ability to manually edit existing classes,
you should be well on your way to creating your own custom themes.
WraPPIng uP 171
This page intentionally left blank
Part III
the
mobIle ApI
12
globAl optIons
On the surface, the jQuery Mobile
framework offers a quick and easy
way to create mobile websites. However,
the framework also has an application programming interface
(API) that can be used to extend the basic functionality. The jQuery
Mobile API provides an extra level of control over the customiza-
tion of your mobile website. Everything from the custom setup
of global options to hooking into interaction events and work-
ing with exposed methods is possible with the API. By the end of
this chapter, you’ll know how to define custom options for your
mobile website and how to write custom code that interacts with
the jQuery Mobile framework.
175
extendIng the mobIleInIt
eVent
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/
p jquery.min.js”></script>
<script src=”assets/js/custom-jqm.js”></script>
<script src=”http://code.jquery.com/mobile/1.0.1/
p jquery.mobile-1.0.1.min.js”></script>
To extend the mobileinit event you must first bind an anonymous callback
function to it, so you execute your custom code when the event fires:
$(document).bind(“mobileinit”, function() {
// Override global options here
});
$(document).bind(“mobileinit”, function() {
$.extend( $.mobile, {
property: value
});
});
Or, you can simply override individual properties by setting them directly using
the $.mobile object:
$(document).bind(“mobileinit”, function() {
$.mobile.property = value;
// Set other properties
});
If you want to update multiple properties, the extend method is a cleaner option
because you don’t need to write the $.mobile object multiple times. However, if
you have only one property to update, setting the property individually requires
less code.
$(document).bind(“mobileinit”, function() {
$.mobile.ns = “jquerymobiletv-”;
});
You can set the ns option to any custom value, such as jquerymobiletv-. Using
the custom namespace produces:
data-jquerymobiletv-foo
Notice that a dash has been included at the end of the namespace; without it
the result won’t include a dash in your namespace, so your data- attributes will
be hard to read and jQuery Mobile will look for an attribute that looks like this:
data-jquerymobiletvfoo
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>Custom Namespace - jQuery Mobile: Design and Develop
p </title>
The nice thing about using custom namespaces is that no other modifications
are necessary; the code has the same results as running a jQuery Mobile webpage
using the default namespaces.
It’s even possible to use Cascading Style Sheets (CSS) selectors to choose certain
HTML elements that include custom data- attributes. For example, you could
select a jQuery Mobile page element and apply CSS to it:
.ui-mobile [data-jquerymobiletv-role=”page”] {
/* Custom CSS here */
}
With the introduction of data- attributes, developers have much more control
over the data that is added to a webpage. Custom attributes provide a means for
supporting semantic HTML, while enhancing the webpage with front-end script-
ing languages, such as JavaScript.
$(document).bind(“mobileinit”, function() {
$.extend( $.mobile , {
autoInitializePage: false
});
});
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>Page Initialization - jQuery Mobile: Design and Develop
p </title>
<link rel=”stylesheet” href=”http://code.jquery.com/
p mobile/1.0.1/jquery.mobile-1.0.1.min.css” />
Running this code delays initialization; the user won’t see the list of names
until the loop has completed and the autoInitializePage property is set to true,
then the jQuery fadeIn method is used to fade in the page.
Figure 12.1 shows how the page renders once the autoInitializePage property
is set to true and the page is faded in.
web-page.html&ui-page=value
it would become:
web-page.html&jqmtv-page=value
Webpages that include the jQuery Mobile framework have a default CSS class that’s
automatically applied to the page element named ui-page-active. But you can
change this default behavior by changing or appending to the default value of the
active page class. The $.mobile object has a property named activePageClass
that can be modified. If this class is replaced with a new value, the default CSS
included with the framework no longer applies its styling to the ui-page-active
class since it no longer exists. Therefore it’s important to create your own custom
CSS class that corresponds to the value you provide for this property or append
an additional class to the ui-page-active class:
$(document).bind(“mobileinit”, function() {
$.extend( $.mobile, {
activePageClass: “ui-page-active ui-jqmtv-page-active”
});
});
By appending an additional custom class, the existing CSS is left intact and the
focus shifts to the CSS that’s used for customizations, rather than every minute
design detail of the framework. A simple CSS file needs to be created and included
to apply some styles to the new custom CSS class:
.ui-jqmtv-page-active {
background: #09C;
color: #fff;
text-shadow: none;
}
This CSS applies a new background color or text color and removes the text
shadowing from the webpage when included in the HTML markup. Here’s an exam-
ple of a simple HTML file that includes the CSS and the custom activePageClass
setting from the previous examples:
With the jQuery Mobile framework added, this code is transformed to include
many additional classes and attributes. The custom ui-jqmtv-page-active class
can be seen in the markup when using any type of browser development tools.
Figure 12.2 shows how the markup is transformed by the framework to include
the new class we created and applied the CSS to.
Another property named activeBtnClass works exactly the same as the
activePageClass. You can set it in the mobileinit callback. It can contain any
string value, and the string value can ultimately relate to a custom CSS class that
you can include in a CSS file. The only difference in the activePageClass and the
activeBtnClass properties is that the activeBtnClass lets you style the active
state of any buttons that are used.
$(document).bind(“mobileinit”, function() {
$.extend( $.mobile, {
ajaxEnabled: false
});
});
This is such a simple property to modify, but it has major results. Setting this
property to false disables URL hash listening and loads all URLs as standard HTTP
requests. Doing so causes page refreshes, disables page preloading and caching,
and eliminates page and dialog transitions. If you’d like your mobile website to
function as a standard website, setting this option to false will create standard
HTTP requests.
By default, pages and dialogs include a transition effect in jQuery Mobile when page
changes are handled via Ajax. The default page transition is slide, while the default
dialog transition is pop. To change these values, target the defaultPageTransition
and/or the defaultDialogTransition properties:
$(document).bind(“mobileinit”, function() {
$.extend( $.mobile , {
defaultPageTransition: “fade”,
defaultDialogTransition: “fade”
});
});
If you run this code, you’ll see that the transitions for pages and dialogs will
both be a fade:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>Page Transitions - jQuery Mobile: Design and Develop
p </title>
<link rel=”stylesheet” href=”http://code.jquery.com/mobile/
p 1.0.1/jquery.mobile-1.0.1.min.css” />
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/
p jquery.min.js”></script>
<script src=”assets/js/custom-jqm-transitions.js”></script>
<script src=”http://code.jquery.com/mobile/1.0.1/
p jquery.mobile-1.0.1.min.js”></script>
</head>
WraPPing up
The jQuery Mobile framework is simple to use, but don’t let its simplicity fool you—
there’s a lot happening behind the curtain. There are many ways to add custom
functionality to create powerful mobile websites and applications. Accessing the
API allows fine-grained control that lets you tell the framework how to behave by
default and even tie into every interaction that occurs on the client side through
events. In the next chapter, you’ll see how events can provide even more control
over your custom jQuery Mobile project.
WraPPIng uP 189
13
hookIng
INto events
jQuery Mobile offers custom events
you can use to extend the function-
ality of the framework, including touch,
scroll, device orientation, page transition, and page initialization,
among others. Hooking into jQuery Mobile events opens up an
entire world of opportunity that can’t be achieved with the basic
framework setup. Knowing the state of a webpage at any given
time provides a level of control you can use to extend existing
functionality. This chapter shows you how to hook into each of
these events to create custom functionality in a mobile website.
191
touch eVents
There are many touch events you can hook into with jQuery Mobile. Keep in mind
that these are available only to touch-enabled devices, so desktop users may not
experience them or any customizations added via an event hook. With that said,
touch events won’t cause errors on desktop devices: they simply won’t function,
because mouse events rule the desktop experience. These events can trigger a
callback function that includes any custom JavaScript. Table 13.1 describes the
five different touch events accessible through the jQuery Mobile API.
Table 13.2 describes the swipe event properties mentioned in Table 13.1.
eVent desCriPtion
tap responds to a quick tap and removal of a finger from the device screen.
taphold responds to a tap of a finger that is left in place on the device screen for about one
second.
swipe responds when a webpage is dragged horizontally or vertically. this is the only event
that has associated properties. these properties are listed in table 13.2.
eVent desCriPtion
scrollSupressionThreshold the default value is 10 pixels. If the value is greater than this, then scrolling is
suppressed.
durationThreshold the default value is 1000 milliseconds. If the interaction is longer than this, then it’s
no longer considered a swipe and nothing occurs.
horizontalDistanceThreshold the default value is 30 pixels. the horizontal displacement of the swipe must be greater
than this.
verticalDistanceThreshold the default value is 75 pixels. the vertical displacement of the swipe must be less
than this.
$(document).ready(function(){
$(“.test-tap-hold”).bind(“taphold”, function(event) {
$(this).html(“Tapped and held”);
});
});
Once the document is ready, the taphold event is bound to an element with the
class name .test-tap-hold. When a finger touches this element and remains on
it, the taphold event is fired. The following example incorporates the JavaScript
file that binds this event to the HTML element:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>taphold- jQuery Mobile: Design and Develop</title>
<link rel=”stylesheet” href=”http://code.jquery.com/
p mobile/1.0.1/jquery.mobile-1.0.1.min.css” />
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/
p jquery.min.js”></script>
<script src=”http://code.jquery.com/mobile/1.0.1/
p jquery.mobile-1.0.1.min.js”></script>
</head>
<body>
<div data-role=”page”>
<div data-role=”header”>
<h1>Page title</h1>
</div>
<div data-role=”content”>
<ul data-role=”listview”>
<li class=”test-tap-hold”>Tap and hold test</li>
</ul>
</div>
<div data-role=”footer”>
Copyright
</div>
</div>
</body>
</html>
As you can see, a listview is included in the page with a list item that contains
a class name of test-tap-hold. When this element is touched and the user’s finger
remains in this position on the screen, the event is fired and the HTML value gets
updated. Figure 13.1 illustrates examples of different touch events.
The events in Table 13.1 let you tie custom code into any state of a mobile
website. Knowing when and how a user is interacting with the screen gives you a
foundation for responding to those interactions.
figURe 13 .2 Webpages
can display vertically or
horizontally depending on
the orientation of the device.
$(document).ready(function(){
$(‘body’).bind(‘orientationchange’, function(event) {
console.log(‘orientationchange: ‘+ event.orientation);
});
});
Of course, it’s also important to bind the event after the document is ready so
the body is accessible, otherwise you’ll receive inconsistent results. You can also
take this code a step further by using the jQuery trigger method to manually trigger
the orientationchange event when the document is ready:
$(document).ready(function(){
$(‘body’).bind(‘orientationchange’, function(event) {
console.log(‘orientationchange: ‘+ event.orientation);
Triggering the event manually when the document is ready makes it possible
to determine the orientation automatically when the page first loads, which other-
wise would not occur. The orientation values are also added to the <html> element
within the webpage and are therefore accessible through CSS. This provides a way
to respond to a device’s orientation via jQuery Mobile and CSS through what is
called responsive design.
responsIve desIgn
With the plethora of devices available on the market today, it’s becoming
more and more important to design websites that display properly in all the
different formats. responsive design is just that: displaying content based on
the device format. this includes device size, device orientation, and even the
way your site reacts to browser resizing on desktop machines. Common ways
of achieving responsive design are through CSS media queries or simply serv-
ing an alternative website. jQuery mobile provides a solution that responds
automatically.
In other words, knowing the device’s orientation at any given time helps you
determine how to render the layout of your content. With this sort of power it’s
not necessary to have multiple websites to handle different devices.
jQuery Mobile offers two scroll events that are triggered when a user scrolls a
webpage: scrollstart and scrollstop. The scrollstart event triggers when a
page scroll begins. Like the orientationchange event, the scrollstart event must
be bound to the body element when the document is ready:
$(document).ready(function(){
$(‘body’).bind(‘scrollstart’, function(event) {
console.log(“scrollstart”);
});
});
The scrollstop event fires when the page scroll stops. Binding the scrollstop
event to the body element works the same way as binding the scrollstart event:
$(document).ready(function(){
$(‘body’).bind(‘scrollstart’, function(event) {
console.log(“scrollstart”);
});
$(‘body’).bind(‘scrollstop’, function(event) {
console.log(“scrollstop”);
});
});
Scroll events can be used together to run custom JavaScript. For example, they
can be used to create a lazy loading effect, functionality that loads images on
demand as they are revealed lower on the webpage during scrolling:
$(document).ready(function() {
var _scrollInterval;
$(document).bind({
scrollstart: function() {
_scrollInterval = setInterval(“onScroll()”, 50);
},
The images are not rendered initially, but as the webpage is scrolled, the images
load when the area of the page they are in is revealed. This functionality produces a
quicker page load time because all the images load the same loader image by default,
rather than loading each unique image until scrolling reveals them on the screen.
The lazy-img class is used to determine which images to load lazily, and the
data-image attribute is used as a reference to the unique image for that tag that is
loaded when the portion of the page is revealed in the browser. There are endless
possibilities for adding custom functionality using the scroll events; this is just one
example, but it is a powerful one that increases the speed at which webpages load.
Imagine knowing when a page transition is going to occur before it even happens.
Add to that knowing ahead of time when a page is going to hide. With page transi-
tion events, this is possible. jQuery Mobile page animations are powered by page
transitions. The animations used during the transition between pages were defined
in previous chapters, but there are also events associated with each step of a page
transition. Events occur before and after each page transition and can be used to
execute custom code at any time during this process. As shown in Figure 13.3, four
events are associated with page transitions, and they occur in sequence.
The first two events occur on the page currently in view when the page transi-
tion begins, and the final two events occur on the page that is coming into view.
Attaching event handlers to these events is easy with the jQuery on method.
You can attach an event handler to a single element for each of the events. In the
following example, the on method is attached to div#my-page and allows custom
event handlers to be created for each of the page transition events. The div with an
figURe 13 .3 The four events
id of my-page is being used as the page container in the HTML document, therefore
associated with jQuery
Mobile’s page transition at any step of page transition these events trigger the custom script that writes to
process. the console:
$(document).ready(function() {
$(‘div#my-page’).on({
pagebeforeshow: function(event, ui) {
console.log(‘This page is about to be shown: ‘+
p ui.prevPage);
},
pageshow: function(event, ui) {
console.log(‘This page was just hidden: ‘+ ui.prevPage);
},
pagebeforehide: function(event, ui) {
console.log(‘This page is about to be hidden: ‘+
p ui.nextPage);
},
As you can see, each event also has event and ui parameters. The event param-
eter is the event object itself, while the ui parameter is a data object that includes
a property that represents a page. Each event’s ui object has a different associated
page property:
jQuery Mobile documentation uses the live method to attach handlers for
page transition events; however, this method was deprecated in jQuery 1.7, and
the delegate method is now being recommended for sites using older versions of
jQuery. Setting up the delegate method is similar to using the on method:
$(document).ready(function() {
$(document).delegate(‘div#my-page’, {
pagebeforeshow: function(event, ui) {
console.log(‘This page is about to be shown: ‘+
p ui.prevPage);
},
pageshow: function(event, ui) {
console.log(‘This page was just hidden: ‘+ ui.prevPage);
},
Being able to hook into page transition events gives you a lot of control. You
can trigger custom code during any step in the page transition process. Knowing
what page will be revealed before it happens gives you access to that page’s HTML
structure, which is useful for discarding unwanted markup, injecting additional
markup into the page, and so on. This also holds true for pages that are about to
become hidden: these events can be used to display a dialog or pop-up window,
carry JavaScript properties from one page to another, and so on. The following
script shows an example of a JavaScript property being carried from one page to
another using these events:
$(document).ready(function() {
$(‘div#my-page’).on({
pagebeforeshow: function(event, ui) {
console.log(‘This page is about to be shown: ‘+
p ui.prevPage);
thePreviousPage = ui.prevPage;
},
pageshow: function(event, ui) {
console.log(‘This page was just hidden: ‘+ ui.prevPage);
},
As you can see, this sort of functionality can be very powerful, yet it’s quite easy
to achieve. Page transition events let you leverage page data at any point during
the jQuery Mobile page life cycle.
The jQuery Mobile framework enhances basic HTML markup. This markup
enhancement magic takes place when page initialization occurs. There are three
steps to the page initialization process; they occur in the sequence defined in
Figure 13.4.
The pagecreatebefore event occurs when the page is inserted into the
DOM, before jQuery Mobile initializes plug-ins and enhances the webpage. The
pagecreatebefore event presents a great opportunity to add markup to a webpage
before the jQuery Mobile framework gets ahold of it and makes enhancements:
$(‘div#my-page’).on(‘pagebeforecreate’, function(event) {
console.log(‘This page is about to be created’);
figURe 13 .4 The three
steps in jQuery Mobile’s page $(‘div#my-page’).attr(‘data-title’, ‘My Page’);
initialization process.
});
(function($){
$.widget(“mobile.logo”, $.mobile.widget, {
// data-attributes that can be used in HTML markup (includes
p default values)
options: {
image: ‘’,
width: 200,
height: 200
},
When the markup for the logo widget is included in the HTML document,
the jQuery Mobile framework makes the enhancements according to the script
in the _create method. The following markup shows how this widget would be
included in a jQuery Mobile webpage:
The pagecreate event is bound to the document, so that when the page is cre-
ated the framework finds the logo widget markup by its role using the :jqmData
selector and then triggers the _create method. In this example, the widget’s _create
method accesses the data-attributes used in the markup to render the widget
accordingly.
$(‘div#my-page’).on(‘pageinit’, function(event) {
console.log(‘This page was just enhanced’);
});
Figure 13.5 shows an example log in Chrome when running a webpage that
includes the initialization and custom widget creation.
Hooking into jQuery Mobile events opens up a world of opportunity. When you
understand how to hook into jQuery Mobile events, you can create virtually any
custom functionality you can imagine. From touch events to device orientation to
page changes and transitions, all events are derived from the user. Knowing when
and how to react to them is priceless.
WraPPIng uP 207
14
workIng WIth
exposed methods
The jQuery Mobile framework
includes numerous methods and
properties that have been exposed on
the $.mobile object. Exposing a method means giving third-party
access to it. In other words, jQuery Mobile offers third-party devel-
opers access to some of the internal methods used throughout
its framework. These methods and properties let you tap into
some core jQuery Mobile functionality to create customizations
that set your mobile application apart from the rest. This chapter
covers changing pages, preloading pages, and a number of utility
methods and properties.
209
chAngIng Pages
progrAmmAtIcAlly
With the changePage method in place, the widget can change pages when a
user selects it. In this example, the hyperlink is expected to be an HTML attribute,
because the widget has an additional property that supports this option. With
this option, each instance of the widget can include its own custom hyperlink in
a data-hyperlink attribute:
ProPerties desCriPtions
allowSamePageTransition When set to false (the default setting), will not execute a request to the same page.
When set to true, allows the same page to be used as the to argument and executes
it. (You might use this property for a form submission that sends form values and
processes them on the same page.)
changeHash Specifies whether or not the hash in the browser’s location bar should be updated. the
default value is true. a hash is a # sign in a url.
dataUrl Value undefined by default, but can be set as a url to update the browser location
when the page changes.
pageContainer Specifies what element the requested page will be contained in.
reloadPage forces the page to reload if a url is used as the value for the changePage method.
role defines the data-role associated with the page when it is displayed.
type Sets the type of request to post or get. the default value is get.
These optional arguments can provide complex functionality. For example, you
can set a request type to submit form values:
$(document).ready(function() {
$(‘#next-btn’).click(function() {
$.mobile.changePage( “step2.php”, {
type: “post”,
data: $(“form#my-form”).serialize()
});
});
});
This might be helpful in a multistep process where form values are carried from
one page to another. The following example includes a form with an input field
for an email address. Rather than a submit button, this form includes an anchor
element with an id of next-btn, which when clicked, triggers the changePage
method in the previous example:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>changePage Form Submission: Step 2 - jQuery Mobile:
p Design and Develop</title>
</head>
<body>
<div data-role=”page”>
<div data-role=”header”><h1>Page Header</h1></div>
<div data-role=”content”>
<form action=””>
<label for=”firstName”>First Name:</label>
<input type=”text” name=”firstName” id=”firstName”>
<label for=”lastName”>Last Name:</label>
<input type=”text” name=”lastName” id=”lastName”>
<label for=”emailAddress”>Email Address</label>
<input type=”text” name=”emailAddress”
p id=”emailAddress” value=”<?php echo
p $_POST[‘emailAddress’]; ?>”>
<input type=”submit” value=”Sign me up”>
</form>
The step2.php page includes additional form input fields to get more informa-
tion from the user before he officially submits the form. This example could be
used as a sign-up form for a newsletter, for example, gathering an email address
and then asking for a first and last name before actually submitting the form. The
emailAddress is carried over from the previous page through PHP’s $_POST array
and written to the corresponding field.
The changePage method is a powerful means to handle not only page changes,
but also form submissions. It allows you to customize page changes in many inter-
esting and unique ways.
Another great $.mobile object method is loadPage. You can use the loadPage
method to load external pages without displaying them. This is a useful way to
preload pages so they display quicker when the user clicks a link. To use this method,
you need to write code much like we did for the changePage method. First, of
course, you have to wait for the document to be ready or the page to be created.
Then, when either of those events triggers, you can call the loadPage event to
preload one or multiple pages:
$(document).ready(function() {
$.mobile.loadPage(“page2.html”);
});
This method is so incredibly easy to use and offers huge benefits. The following
example embeds a JavaScript file that includes the loadPage code:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html;
p charset=UTF-8”>
<meta name=”viewport” content=”width=device-width,
p initial-scale=1”>
<title>loadPage- jQuery Mobile: Design and Develop</title>
<link rel=”stylesheet” href=”http://code.jquery.com/
p mobile/1.0.1/jquery.mobile-1.0.1.min.css” />
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/
p jquery.min.js”></script>
<script src=”http://code.jquery.com/mobile/1.0.1/
p jquery.mobile-1.0.1.min.js”></script>
<script src=”assets/js/custom-jqm-loadpage.js”></script>
</head>
<body>
As soon as the page is loaded and the document is ready, the page2.html file
loads silently in the background before any link is clicked. When the user clicks
the anchor element that links to the page2.html page, the file displays immediately.
Figure 14.1 shows an example of the markup after the page has been loaded via
the loadPage method. As you can see, the page has been loaded and inserted into
the bottom of the current page.
The loadPage method includes a required url argument that can be a string
representing a relative or absolute URL or it can be an object. Table 14.2 lists the
properties available in a loadPage request.
ProPerties desCriPtions
data Sends data to the page being loaded, similar to the data
property in the changePage method.
pageContainer Specifies the element that will contain the page after it has
been loaded.
jQuery Mobile has several built-in utility methods that provide useful functionality
when developing a website. Table 14.3 lists the current utility methods supported
by the framework and a description of what each of them does.
Methods desCriPtions
$.mobile.showPageLoadingMsg Shows the loading message, which can be done at any point in time. useful when
dynamically modifying the page.
$.mobile.fixedToolbars.show displays fixed headers and footers of the active page. a single, optional, Boolean
argument named immediately can be set to true to immediately show the header
or footer. By default this argument is false, which fades in the header and footer
after 100 milliseconds.
$.mobile.fixedToolbars.hide hides fixed headers and footers of the active page. Includes a single, optional
argument named immediately, as in the $.mobile.fixedToolbars.show method.
$.mobile.path.parseUrl parses a url into an object. the resulting object includes 16 properties, which are
listed in table 14.4.
$.mobile.base Works with the generated base element. jQuery mobile generates a base element
in the head of the html file that is updated automatically when a new page is
loaded. this element keeps a reference to the currently loaded page so all assets
are loaded from the proper location.
$.mobile.silentScroll accepts one argument that can be used to scroll a page to a specific Y position.
does not trigger the scroll event listeners.
ProPerties desCriPtions
hash represents the portion of the url that comes directly after the # and includes the # character.
pathname represents any path or directory and the current file referenced in the url.
protocol represents the protocol of the url, most often http: or https:.
authority If specified, represents the username, password, and host components of the url.
directory Similar to pathname, but includes only the path or directory, not the actual current filename.
domain Includes the full domain name, port (if specified), and protocol.
hrefNoHash If a hash exists, returns the entire original href value, minus the hash character and associated
hash value.
hrefNoSearch If a query string exists, returns the entire original href value, minus the query string.
To use any of these utilities, simply wait for the page to load and access them
through the $.mobile object. These utility methods and properties offer quick ways
to access or alter data needed when developing with jQuery Mobile. You may even
WraPPing up
Accessing exposed methods and properties offers a way to tap directly into the
jQuery Mobile framework and interact with code functionality to create custom-
ized mobile applications. There’s a lot happening behind the scenes with this
simple framework, and there are many ways to add custom functionality to provide
powerful mobile websites and applications. By tapping into the API you can create
any functionality you need.
CMS
15
InstAllIng
a moBIle
wordpress theme
WordPress is a powerful content
management system (CMS) that
began as a way to create simple blogs
and websites. It’s currently used by over 60 million people and
growing. WordPress development is in demand and having the
ability to create mobile WordPress websites just adds to the appeal.
This chapter starts from the beginning, showing you where and
how to install WordPress on a web server, then explains where to
get the jQuery Mobile WordPress theme and how to install it, and
finally shows you how to create new pages and blog posts.
227
getting stArted
You have two options when creating a WordPress website. The first is to visit
wordpress.com and create a blog on their huge network. The second, and the one
we’ll be using in this chapter, is to visit wordpress.org and download WordPress
to install on your own server using what they call their “famous 5-minute instal-
lation.” As you’ll see in this chapter, it’s actually true, but first you need to have a
web server and a database installed. If you don’t have a web server of your own,
WordPress recommends the web hosts listed on http://wordpress.org/hosting/,
or you can find a web host of your choice. The only caveat is that your web server
needs to have PHP and MySQL to run WordPress.
installing WordPress
Once you have a web server set up, you’ll need to upload the WordPress files
and then download a MySQL database to configure WordPress. You can find the
WordPress configuration in the wp-config.php file. For the database, there are a
number of free MySQL apps you can download and use. For the example in this
chapter, we’ll use Sequel Pro for Mac OS, which you can download at www.sequelpro.
com, and we’ll create a database named jqm-wp using Sequel Pro (Figure 15.1).
With the database in place, the last step is to add the database login data to
the WordPress configuration file or, as mentioned previously, wp-config.php
(Figure 15.2). Again, this file is what contains the server configuration data for
WordPress. You’ll need to at least complete the DB_NAME, DB_USER, DB_PASSWORD,
and DB_HOST variables to get WordPress to point to your database.
The names are pretty self-explanatory, but it’s important to know what they are.
Table 15.1 lists the variable names along with brief descriptions of each.
DB_NAME the name of the database. as an example, we named our database jqm-wp, as shown in
figure 15.1.
DB_HOST the host name for your database. this value is typically localhost, but it can sometimes be the
same as your domain name or something completely custom based on your web host.
With the database set up, visit the site and complete the installation process
by adding a site title and creating an admin user (Figure 15.3). Remember the
password you use when creating this account, because you’ll need it when you’re
finished with the installation.
That’s it! With WordPress installed, you can now log in to the WordPress admin-
istration area using the username and password you just entered. Within the admin-
istration area, you can completely manage your website. For example, you can
create webpages, blog posts, and users, as well as install plug-ins and themes. With
that said, now it’s time to set up the jQuery Mobile theme for our sample website.
Adding a theme to WordPress is super easy. All you need to do is download, buy,
or create a theme, and then upload it to the wp-content/themes directory within
your WordPress site. Once there, you need to activate the theme and voilà, you’re
finished. The following example uses a jQuery Mobile theme from Francis Robert, a
freelance web programmer who has the most functional jQuery Mobile WordPress
theme I’ve found to date. You can find it in the WordPress category of his blog at
http://frobert.com. (Thanks, Francis! It’s great to see developers sharing great
things with each other.)
Once you’ve downloaded the jQuery Mobile theme, you can upload it to the
wp-content/themes directory, as mentioned previously. After uploading the theme,
log in to the WordPress administration area and visit the Appearance > Themes
page from the left sidebar. Once there, select the Activate link under the jQuery
Mobile theme (Figure 15.4).
To create more pages and blog posts, you simply need to log in to the WordPress figURe 15 .7 (Left) Creating
administration area. Once logged in, you can manage all of your content from the a new blog post.
navigation in the left sidebar. To create a new blog post, select Posts > Add New
figURe 15 .8 (Right) Viewing
(Figure 15.7). a new blog post.
From this webpage you can add a title and a description, and choose a category
and tags. You can save the blog post as a draft or publish it by clicking the blue
Publish button in the top-right module. Once published, you can view the blog
post by visiting the home page of your WordPress website (Figure 15.8).
Once complete, the page titled Home will be the front page and the page titled
figURe 15 .12 (Right) The final
Blog will be the page where the blog posts are listed (Figure 15.12). WordPress jQuery Mobile
website.
WraPPing up
Who would have thought that setting up a mobile content management system
would be so easy? Using WordPress and the jQuery Mobile theme discussed in
this chapter, you can have a mobile CMS up and running in no time. The fun part
is customizing it using the techniques learned throughout this book. WordPress
lets you alter theme files to create further customizations. You can literally start
editing the theme files and making updates that will affect how your site renders.
You can also add custom HTML to your WordPress pages, which can include the
widgets covered in this book, such as linked lists, collapsible content, and so on.
WraPPIng uP 235
16
InstAllIng a
moBIle drupAl
theme
Drupal is another content manage-
ment system (CMS) that powers
millions of websites and applications.
As with WordPress, you can build blogs, websites, and even enter-
prise applications by adding your own customizations or by incor-
porating modules and themes from the Drupal community. This
chapter shows you where and how to install Drupal on a web server,
then explains where to get the jQuery Mobile Drupal theme and
module, how to install them, and how to create new pages.
237
getting stArted
figURe 16 .1 A database
named jqm-drupal is added to
store Drupal data.
To get started with Drupal you must first visit the website at www.drupal.org and
download the core. The core includes the files needed to run Drupal on a web
server. If you don’t have a web server of your own, any of the options mentioned
in Chapter 15, “Installing a Mobile WordPress Theme,” will work. This includes the
web hosts listed on http://wordpress.org/hosting/ or any web host of your choice.
Again, as with WordPress, the only caveat is that your web server needs to have
PHP and MySQL in order to run Drupal.
installing druPal
Once you have a web server set up, you need to upload the Drupal files then down-
load a MySQL database to configure Drupal. There are a number of free MySQL
apps you can download and use for the database. This example uses Sequel Pro
for Mac OS, which you’ll find at www.sequelpro.com. For the sample in this chap-
ter, we’ll be creating a database named jqm-drupal using Sequel Pro, as shown in
Figure 16.1.
With the database set up, visit the site and complete the six-step installation figURe 16 .3 Choose a
process. The first step is choosing a profile (Figure 16.2). Unless you know exactly language for the Drupal
installation process.
what you want, choose the Standard option, because it includes common features
to prevent you from wasting your time reinventing the wheel with your Drupal
configurations.
Now it’s time to choose the language (Figure 16.3). By default, English is the
only option, but you can click the link in this webpage to learn how to install
Drupal in other languages.
account. It’s important to remember this login information: You’ll need it to log in
to the Drupal administration area.
Finally, you’ll see a congratulations screen, and you can view your new Drupal
website (Figure 16.6).
With Drupal installed, you can log in to the Drupal administration area using
the username and password you just entered. Within the administration area, you
can completely manage your website: You can create webpages, blog posts, and
users, as well as install modules and themes. Now it’s time to set up the jQuery
Mobile theme for our sample website.
Adding a jQuery Mobile theme to Drupal is fairly easy, but not as easy as with
WordPress. Drupal requires two items to be installed to use a jQuery Mobile theme:
the jQuery Mobile module and the jQM theme.
The first step in this process is to create a directory named libraries in the
sites/all directory (Figure 16.8).
Within that directory, create a directory named jquery (Figure 16.9).
$conf[‘jquerymobile_front] = 0;
$conf[‘jquerymobile_ns] = ‘’;
$conf[‘jquerymobile_autoInitializePage] = ‘’;
$conf[‘jquerymobile_subPageUrlKey] = ‘’;
$conf[‘jquerymobile_activePageClass] = ‘’;
$conf[‘jquerymobile_activeBtnClass] = ‘’;
$conf[‘jquerymobile_ajaxEnabled] = ‘’;
$conf[‘jquerymobile_hashListeningEnabled] = ‘’;
$conf[‘jquerymobile_defaultPageTransition] = ‘’;
$conf[‘jquerymobile_defaultDialogTransition] = ‘’;
$conf[‘jquerymobile_minScrollBack] = ‘’;
$conf[‘jquerymobile_loadingMessage] = ‘’;
$conf[‘jquerymobile_pageLoadErrorMessage’] = ‘’;
At last it’s time to activate the module in the Drupal administration area. Visit
the modules section and locate the jQuery Mobile module, which should appear
under the Mobile section (Figure 16.12).
tings, visit the Modules page, scroll until you find the jQuery Mobile module, and
select the Configuration link next to the module. On this page you’ll see an area
titled File Settings, shown in Figure 16.16. If you select this title, it will expand and
reveal text inputs you can use to set the version of the jQuery library and jQuery
Mobile framework as well as the file path location for the files that were uploaded
to the Drupal installation in Figure 16.10.
figURe 16 .17 (Left) Create To create more pages and blog posts, you need to log in to the Drupal administra-
a blog post in Drupal. tion area. Here you can manage all your content from the Content page: Select Add
content to choose a content type. On this page, there are two default content types:
figURe 16 .18 (Right) Drupal
site with a blog post. Article and Basic page. To create a blog post, select Article, enter a title, and write
your post in the Body field in the web form seen in Figure 16.17.
By default, this blog post appears on the home page of your Drupal website
(Figure 16.18).
To create a page, go back to Content, select Add Content, and select Basic page.
Use the web form on this page to create your page. In this example, we’re creating
a page named Home, which will ultimately become the front page for the website
(Figure 16.19).
You can use this new page as the front page for the Drupal installation. To define
a page as the front page, visit the Configuration page, select Site information, and
scroll down until you see Default front page. Here you’ll see the URL of your Drupal
website with a text input to enter the node ID of the page you want to use. You can
find this node ID in the browser address bar when viewing any basic page; in this
example, our node ID is 1, so we’ve entered node/1 into the text input (Figure 16.20).
That’s it! Figure 16.21 shows the final Drupal website with a custom front page.
WraPPing up
Using Drupal and the jQuery Mobile theme and module from this chapter lets you
create a powerful mobile CMS and have it up and running in no time. With the
techniques you’ve learned in this book, you can create unique and custom webpages
figURe 16 .21 The final jQuery
with widgets, formatting, and other functionality provided by the jQuery Mobile Mobile Drupal website with a
framework. Now there’s nothing holding you back from creating a powerful CMS custom front page.
with complete mobile capabilities.
WraPPIng uP 249
This page intentionally left blank
V
BeYoNd
jQuery mobIle
17
detectIng
moBIle devIces
Mobile websites are often developed
separately from primary websites
(those intended to be viewed on a desk-
top or laptop), although they may use much of the same content.
To make sure your website is tailored for mobile devices, you’ll
want to detect when a mobile device visits the site and then redi-
rect the device to markup made especially for mobile. You may also
want to deliver a website layout and content based on a specific
mobile device. In this chapter, you’ll learn how to do both. Let’s
begin by learning how to detect when a mobile device accesses
your website.
253
PHP
Since PHP is one of the most popular scripting languages on the web, let’s look at a
PHP function that performs mobile detection across a wide array of mobile devices.
The function is simple and can be extended and modified easily:
function mobile_detect(){
$mobile_devices = ‘/(alcatel|amoi|android|avantgo|blackberry
|benq|cell|cricket|docomo|elaine|htc|iemobile|iphone|ipad|ipaq|ipod
|j2me|java|midp|mini|mmp|mobi|motorola|nec-|nokia|palm|panasonic
|philips|phone|sagem|sharp|sie-|smartphone|sony|symbian|t-mobile
|telus|vodafone|wap|webos|wireless|xda|xoom|zte)/i’;
if(preg_match($mobile_devices, $_SERVER[‘HTTP_USER_AGENT’])) {
return true;
} else {
return false;
}
}
the regular expression string in the example doesn’t begin to cover all the mobile devices with unique user
agent strings available today. there are literally hundreds of different types of mobile devices capable of
surfing websites.
how do you decide which ones to include in your test? honestly, only you can answer that because it
depends on the audience for your mobile website or application.
You’ll find many online sources for user agent information. one such source is www.useragentstring.com on
which the list of mobile devices is regularly updated and very accurate. You can find the mobile device list at
www.useragentstring.com/pages/mobile Browserlist/.
While learning regular expressions may be dreadful and scary, it can be a valuable part of your program-
ming toolkit. fortunately, there are many resources available online. here are some recommended websites:
www.regular-expressions.info/ covers a wide range of materials for developing, testing, and using regular
expressions.
http://regexlib.com/ provides a searchable library of commonly used regular expressions—perfect for the
developer who doesn’t want to write his own!
http://regexpal.com/ makes it easy to develop and test regular expressions in real time.
include(‘path/to/mobile_detection.php’);
$mobile_device = mobile_detect();
// Perform a redirection if a mobile device is detected
if($mobile_device == true) {
header(‘Location: http://m.mywebsite.com’);
exit();
}
The code here is fairly self-explanatory. You store the result of the function in
a variable named $mobile_device and test that variable to see whether it’s true
or false. If it’s true, you redirect the mobile device’s browser to the content you
want that device to consume. You can use the function on any page and set custom
redirections if you like. The result of the current function redirects the browser to
http://m.mywebsite.com, as seen in Figure 17.1.
You could return the user agent string from the function so you could perform
certain actions based on which kind of device is accessing the website. Rather than
do that, let’s learn how to detect specific devices with JavaScript when the browser
arrives at the mobile site.
In some cases, you’ll want to know what specific mobile device is accessing your
mobile website or application so you can have some control over the user’s experi-
ence. This control might come in the form of enabling or disabling certain functions
or displaying data and content tailored to the user’s specific device.
The technique is surprisingly similar to the method we used for PHP. Let’s exam-
ine a couple of ways to detect a specific mobile device, first using pure JavaScript
and then using jQuery.
As you can see, you’re using a regular expression to look for a match to the user
agent string. JavaScript gathers user agent information in its navigator object, and
you can access that information in navigator.userAgent.
On an iPhone 4 using Safari as the browser, the user agent string might look
something like this:
$.support.boxModel;
J opacity will be true if the browser supports this CSS property (all IE brows-
ers will return false as they use alpha filters).
J submitBubbles will be true if a submit event can bubble up the DOM tree.
Detecting when a mobile device accesses your website and getting specific infor-
mation about that device could not be easier to do now that you have a solid code
foundation for building your jQuery Mobile websites and applications.
You have several good tools available to you for configuring and testing regular
expressions and digging deeper into user agent strings. With a firm grasp of these
tools, it’s easy to develop mobile device detection for any website.
The next question is, “How do I test my websites on as many mobile devices as
possible?” Most of us can’t afford to purchase all the mobile devices available, so
we’ll turn our attention to mobile device simulators. That’s up next!
WraPPIng uP 261
18
testIng WIth
sImulAtors
When it comes to testing mobile
websites and applications, you
have several options: You can use the
browser on the desktop where you develop your markup and code,
a mobile device, or a mobile simulator. Each has advantages and
disadvantages.
263
explorIng your
testIng optIons
If you test on the desktop, you can get immediate results. The downside is that,
even resized, a desktop web browser won’t offer the same experience as a mobile
device. For example, scroll bars are much wider and more intrusive on a desktop
web browser. Using a desktop browser is good for immediate spot checks.
Most mobile developers have two or three physical devices available for testing,
but can’t afford to purchase more than that. One solution is “crowd testing,” where
you ask your friends to access your website or application via their devices and
give you feedback about any issues they find. Another solution is using remote labs.
Testing in remote labs can be expensive, but it lets you test your sites in multiple
devices from the comfort of your desk.
Another option is using a mobile simulator. Mobile simulators are evolving and
come in a couple of flavors: ones you work with online and ones you download
and install on your desktop. Some simulators come with mobile development tool
packages and software development kits (SDK). All typically offer the same sort
of immediate feedback that testing on your desktop browser does. The downside
is that you can’t interact with simulators using gestures available to you on many
touch-enabled mobile devices, and sometimes a simulator may not be configured
in a way that duplicates the mobile device’s browser and operating system.
Let’s dig in and find some mobile simulators.
one of the most important questions you need to ask yourself is, who am I developing my mobile
website for?
Since you’re focused on developing websites and applications using jQuery mobile, this chapter talks about
simulators that deliver the proper experience in a full-fledged mobile web browser typically available on
smartphones and pads used by a great many mobile customers today.
there are other simulators available for mobile devices that don’t deliver the same kind of experience you’d
expect from a fully capable web browser. If you expect that your website visitor will be using these kinds
of devices, I strongly recommend that you look into these simulators and learn how to use them as well.
developing for these devices may mean that you have to add code to redirect or strip down your site to
accommodate these users.
You should answer the question of who you’re designing your mobile website for at the outset of your plan-
ning process. Knowing your target audience and the devices you anticipate they use will make development
and testing go much more smoothly.
Finding solid online mobile device simulators is akin to finding your prince (or figURe 18 .2 The uncluttered
princess). You have to kiss a lot of frogs first. Enter “mobile device simulator” into layout of the website at
mobilephoneemulator.com.
Google, and the results can be staggering and frustrating. The user agent string inherited
You’ll need to take into account that most online simulators are affected by the its attributes from the parent
browser you use to access the simulator. Most online simulators tend to inherit the browser.
characteristics of the parent browser and many do not present or honor attributes
such as mobile user agent strings or visual elements present in mobile device
browsers. We’ll talk more about those issues in the “Using Simulators for Testing”
section later in this chapter.
Here are some of the better simulators you’ll find online:
J Cowemo at www.mobilephoneemulator.com/
The great thing about this mobile emulator is that it offers several different
smartphone layouts. The menu allows you to easily switch between mobile
devices and orientation, as shown in Figure 18.1.
you may be working with locally (localhost); you must upload your sites to
a server accessible from the web.
If you’re testing layout, this is a great tool. You can switch between devices
quickly. Devices are rendered with the proper screen width and height
(there’s a mode to enlarge the screen size so you can attend to details), which
makes it perfect for capturing screenshots of your sites on different devices.
Although Opera Mini may not be one of the most widely used browsers, a
growing number of people choose to download it and use it instead of the
browsers that come packaged with their mobile devices. The online test
site (Figure 18.3) is clean and easy to use.
Be aware of the way that Opera Mini interprets Cascading Style Sheets (CSS).
Sometimes, more complex layouts aren’t rendered as you would expect.
It does correctly report most user agent strings if you need those to be
available when testing, and you must upload your sites to a web-accessible
server to test.
This simulator is great, but it has some limitations, such as offering only
four different screen layouts and inheriting the user agent string from the
parent browser. It also uses a desktop browser scroll bar that may affect
your site’s layout. Have a look at Figure 18.4, and you’ll see how the scroll
bar eats up some screen real estate.
One significant advantage is that you can test from your local machine
without having to upload your site files to a web server. Having the ability
to quickly check your layout is a real plus for any mobile device emulator.
Now that you have some simulators in your toolbox, it’s time to incorporate them
into your development workflow. Let’s start by testing in the online emulators.
there’s a solution you can use during the testing process that will let you modify the request header so that
the proper user agent strings are sent to the server. You must be using a mozilla firefox browser with the
modify headers add-on. You can get the add-on at:
https://addons.mozilla.org/en-uS/firefox/addon/modify-headers/
If you choose to use this tool, you’ll want to educate yourself on user agent strings and how to form them.
that information is available from the World Wide Web Consortium at:
www.w3.org/protocols/http/htrQ_headers.html
this tool provides a handy user interface that can be easily started from firefox’s add-on toolbar. I encour-
age you to make it a part of your mobile development toolbox.
You generally have two options: Some labs wire the device to a server that’s
controlled from the tester’s computer; others allow you to monitor the test via a
remotely accessible camera. This latter approach requires an on-site tester, and the
tester will interact with the device. Some labs even offer automated scripted tests.
WraPPing up
There are a lot of options for testing your mobile websites and applications, and
you’ll have to be diligent in setting up and using simulators with well-defined test
plans to ensure success.
As a developer, you’ll likely include a combination of online and desktop simu-
lators in your workflow to test the functions and features of the mobile websites
you develop. Once you’ve reached a certain stage of development, you may want
to extend your testing to mobile labs (if they are in your budget).
The one simulation you’ll always want to include is interacting with your mobile
sites on as many physical devices as possible. This can be limited to the devices that
are immediately available to you or can involve getting your friends and acquain-
tances together for a round or two of hands-on examination. Don’t forget the pizza!
WraPPIng uP 271
Index
272 Index
C click event
adding to logo widget, 210–211
caching webpages, 52–54 applying, 11–12
in DOM (document object model), 54 example of, 8–10
using API, 54 using bind method with, 46
caret (^), using in regular expressions, 46 CMS (content management system), 227, 237.
CDN (content delivery network), 6 See also Drupal; WordPress
CDN-hosted files collapsible content area, example of, 164
obtaining, 31 collapsible content, nesting, 100–101
referencing, 30 collapsible content widget. See also jQuery
changePage method Mobile widgets; widgets
setting to step2.php, 215–216 creating accordions, 101–102
triggering, 213–214 described, 99
using, 210–216 using, 99–100
changePage properties color blocks, dragging, 160
adding to options argument, 213 color swatches, 158–159
allowSamePageTransition, 212 content area, separating data-theme
changeHash, 212 from, 165
data, 212 content delivery network (CDN), 6
dataUrl, 212 content theming, 163–164. See also
pageContainer, 212 form element theming; theming
reloadPage, 212 components
reverse, 212 controlgroup, select menu in, 149
role, 212 copyright notices, including in footers, 82
showLoadMsg, 212 count bubble
transition, 212 adding to list item, 115–117
type, 212 adding to listview, 169
checkboxes, 141–145 Cowemo online simulator, 265–266
applying mini, 145 crowd testing, 271. See also testing
controlgroup data-role groups, 142 custom data
disable method, 145 accessing, 24
enable method, 145 using, 24
events, 145 custom namespaces, using, 24–26. See also
horizontal toggle set, 143–144 namespaces
legend in fieldset, 142 customizing code, 178
questions, 142
versus radio buttons, 141
refresh method, 145 D
setting theme, 145 dash (-)
statements, 142 using at end of namespaces, 178
versus text inputs, 145 using with custom namespaces, 25
checkmark icon, using, 72–73 data- attributes
Chrome Developer Tools, using, 37 adding to image tags, 24
clearQueue method, 13–14 for buttons, 70
Index 273
data- attributes (continued) delay method, 13
custom namespaces, 24–26 Delete button, combining with Save, 80
customizing, 178 dequeue method, 13
data-role custom attribute, 25, 32–33 desktop simulators, testing with, 270.
explained, 24 See also testing with simulators
preventing name clashing, 24–25 detecting devices. See device detection
values, 24 device detection
data-collapsed attribute, using, 100 using JavaScript, 257–260
data-divider-theme, using, 168 using PHP, 254–256
data-filter attribute, adding, 122–123 dialog transitions
data-filter-placeholder attribute, using, altering, 188–189
123–124 pop, 188
data-filtertext attribute, adding, 130–131 dialog windows
data-hyperlink attribute, using with creating, 62–68
changePage method, 211 as external webpages, 64–65
data-prefetch attribute, using, 52 flip transition, 68
data-rel attribute max-width, 67
setting to back, 51 multipage, 62–63
setting to dialog, 62–63 overwriting widths, 67
data-role attribute pop transition, 68
for button, 69–70 as pop-up windows, 66–68
button setting, 80 single-page, 65
collapsible value, 99 slidedown transition, 68
collapsible-set value, 101–102 transitions, 68
defining pages, 32 .ui-dialog classes, 67
described, 25 dialog-window.html file, 64–65
header value, 76 display, responsive design, 196
list-divider value, 114 displaying content, considering, 23
listview value, 106 div.foo jQuery object
navbar value, 85 binding click event to, 8–9
data-split-icon attribute, using, 113 clicking, 13
data-split-theme, using with listview, 170 <!DOCTYPE> declaration, 20
data-theme attribute document.ready event, using with touch
applying to form elements, 166 events, 193
described, 25 documents, waiting for loading, 11–12
in listview, 166–167 Drupal. See also CMS (content management
separating from content area, 165 system); WordPress
using with linked lists, 107 adding content, 248–249
data-title attribute, 43 blog posts, 248
default page transitions, altering, 188–189 creating pages, 248–249
defaultDialogTransition property, custom settings, 247
targeting, 188 database configuration, 240
defaultPageTransition property, defining front page, 248–249
targeting, 188
274 Index
downloading, 238 filter.js file, using, 126–128
installing, 238–241 Firefox, Modify Headers add-on, 269
installing jQuery Mobile theme, 246 flip toggle switches, 154–155
jquery directory, 243–244 making, 154
jQuery Mobile module, 242–245 versus sliders, 155
jQuery Mobile theme, 246 flip transition
language selection, 239 using, 55, 57
libraries directory, 243 using with dialog windows, 68
node ID, 248–249 font styling, adding, 92–93
profile selection, 239 footer component, applying swatch to, 162
Sequel Pro for Mac OS, 238 footer toolbars
site configuration, 240 markup, 82
theming with jQuery Mobile, 242–247 using, 82
form element theming, 165–170. See also
content theming; theming components
E form elements
email folders, using count bubbles with, anchor with id of next-btn, 213–214
116–117 applying data-theme to, 166
emailAddress; input, 215–216 changing swatches on, 166
emulators, testing with, 268 checkboxes, 141–145
“Error Loading Page” message, 58 emailAddress; input, 215–216
events. See also mobileinit event flip toggle switches, 154–155
binding to elements, 9 radio buttons, 141–145
customizing, 11 select menus, 146–151
managing, 8–11 sliders, 152–154
orientation, 195–196 text inputs, 134–140
page transition, 200–203 functions
scroll, 197–199 managing, 8–11
touch, 192–194 versus methods, 10
exposed methods. See also methods; utility
methods
changePage, 210–216
G
data-hyperlink attribute, 211 gear icons, using with split button lists, 113
explained, 209 global options
loading pages, 217–218 active button classes, 184–186
external links, using, 49–50 active page classes, 184–186
customizing namespaces, 178–179
customizing subPageUrlKey, 183
F default page transitions, 188–189
fade transition, using, 55 delaying page initialization, 180–182
fieldset, controlgroup data-role, 148 dialog transitions, 188–189
filterCallback option, using with search disabling Ajax navigation, 187
filters, 126 enabling Ajax navigation, 187
filtering items, 123 extending mobileinit event, 176–177
Index 275
grid columns HTML files
adding custom CSS to, 93–94 anchors, 46
block-title custom class, 93–94 single-page templates, 45
ui-bar-a class prefix, 92, 98 using on webpages, 35
ui-block class prefix, 90 HTML5, data attributes. See data- attributes
ui-grid-a class prefix, 90 HTML5 template. See also multipage
grid rows, 97–98 template; single-page template
grids adding framework to, 31
columns, 90–97 creating, 20
creating, 90 <!DOCTYPE> declaration, 20
CSS class, 90 viewport meta tag, 22
described, 90 hyperlinks
rows, 97–98 applying transition effects to, 189
toolbar layouts, 95–97 converting to buttons, 69
two-column layout, 90–91 markup, 48
ui-grid-c class, 97 markup for Ajax, 47
pound sign (#) in, 46
H
hashtags, managing history with, 45–46 I
header component, applying swatch icons
to, 162 adding to list items, 118–119
header element, adding Save button customizing, 72
to, 78–80 including on buttons, 71
header toolbars id value, referencing, 44
CSS classes, 77 image tags, adding data- attributes to, 24
grouping buttons, 80 input elements, using buttons with, 70
heading element, 77 inset lists, creating, 111
markup, 77 installing
navbars in, 85–86 Drupal, 238–241
with page title, 76 JQuery Mobile module, 242–245
ui-title class, 77 WordPress, 228–230
without page title, 76 internal links, using, 49–51
“Hello world!” blog post, accessing, 232
history, managing with hashtags, 45–46
home data icon, using, 71–72
J
home page, setting in WordPress, 235 JavaScript
HTML elements. See also semantic HTML device detection, 257–260
accessing by ID, 7 match() method, 258
.class selector, 8 navigator object, 257
scope, 9 regular expressions, 257–259
selecting, 7–8 switch statement, 258–259
targeting, 8 user agent information, 257–258
$(this), 9–10, 12 JavaScript Object Notation (JSON), 213
276 Index
jqm-wp database, creating, 228 link types, 48
jQuery framework for Ajax, 47
cross-browser compatibility, 7 disabling Ajax, 47, 49–50
described, 5 external, 49–50
downloading, 6 internal, 49–51
selecting HTML elements, 7–8 linked lists
jquery() function, using with HTML data-theme attribute, 107
elements, 7 described, 106
jQuery Mobile framework inset, 111
adding to HTML5 template, 31 listview value, 107
adding to websites, 30–31 nested, 109–110
A-grade support, 47 numbered, 109
B-grade support, 47 pointer cursor, 107–108
C-grade support, 47 ui-btn class, 107–108
downloading packages, 30 ui-btn-icon-right class, 108
ns option, 25 ui-listview class, 107
obtaining, 30 list dividers
referencing CDN-hosted files, 30 adding themes to, 168
.support method, 259–260 creating, 114
version 1.1.0, 135 using, 116–117
jQuery Mobile module list items, filtering, 130–131
configuring settings, 247 lists
downloading, 242–245 count bubbles, 115–119
jquery.custom directory, 244 customizing, 112–119
variables in settings.php, 244–245 icons, 118–119
jQuery Mobile theme linked, 106–111
custom settings, 247 search filter bars, 122–123
installing for Drupal, 246 split button, 112–113
jQuery Mobile widgets, 183. See also thumbnails, 117–118
collapsible content widget; widgets listview
jquerymobiletv- namespace, customizing, adding id for, 126–128
178–179 count bubble theme, 169
JSON (JavaScript Object Notation), 213 data-divider-theme, 168
data-split-theme, 170
data-theme in, 166–167
K with “e” swatch data-theme, 167
Keynote DeviceAnywhere remote lab, 269 using with search filter text, 125–128
listview theme
L customizing, 167
overriding with list items, 167
landscape value, using with orientation loading messages, customizing, 58
property, 195 loading webpages, 197–199
lazy loading effect, creating with scroll loadingMessage property, setting, 58
events, 197–199
Index 277
loadPage method Mobilizer, 270
markup, 219 online, 265–267
url argument, 218 using, 264
using, 53, 217–220 mobile web, developing for, 264
loadPage method arguments mobile webpages. See also webpages
data, 53 Chrome Developer Tools, 37
loadMsgDelay, 53 page data-role attribute, 35–36
pageContainer, 53 structuring, 34–37
reloadPage, 53 using separate HTML files, 35
role, 53 XMLHttpRequest, 36–37
type, 53 Mobile Websites 4U simulator, 267
loadPage properties mobile_detection.php file, 256
data, 218 $.mobile.base utility method, 220
loadMsgDelay, 218 mobile-device detection
pageContainer, 218 using JavaScript, 257–260
reloadPage, 218 using PHP, 254–256
role, 218 $.mobile.activepage property, 221
type, 218 $.mobile.fixedToolbars.hide utility
logo widget method, 220
creating, 204–205 $.mobile.fixedToolbars.show utility
height option, 204–205 method, 220
image option, 204–205 $.mobile.hidePageLoadingMsg utility
width option, 204–205 method, 220
mobileinit event. See also events
$.mobile object, 177
M anonymous callback function, 176
messages custom JavaScript handler, 176
loading, 58 extending, 176–177
suppressing display of, 58 overriding global options, 177
methods versus functions, 10. See also overriding properties, 177
exposed methods; utility methods setting properties, 177
minification, benefit of, 6 updating properties, 177
Mob4Hire crowd testing, 271 using with search filter text, 124–125
mobile devices, list of, 254 $.mobile.path.isAbsoluteUrl utility
$.mobile object method, 220
activePageClass property, 184 $.mobile.path.isRelativeUrl utility
extending, 180 method, 220
loadPage method, 217–220 $.mobile.path.isSameDomain utility
mobileinit event, 177 method, 220
subpageUrlKey property, 183 $.mobile.path.makePathAbsolute utility
$.mobile property, ns, 177 method, 220
mobile simulators $.mobile.path.makeUrlAbsolute utility
finding online, 265–267 method, 220
278 Index
$.mobile.path.parseUrl utility method, 220 navbars
authority property, 221 with button icons and logo in header, 86
directory property, 221 in header toolbars, 85
domain property, 221 and logos in headers, 86
filename property, 221 with wrapping buttons, 85
hash property, 221 navigation bars
host property, 221 creating, 85–86
hostname property, 221 wrapping, 85
href property, 221 nested lists, creating, 109–110
hrefNoHash property, 221 ns option
hrefNoSearch property, 221 $.mobile property, using, 177
password property, 221 using with data- attributes, 25
pathname property, 221 number patterns, using, 135
port property, 221 numbered lists, creating, 109
protocol property, 221 numeric keyboard, 134
search property, 221
username property, 221
mobilephoneemulator.com
O
layout, 265 online emulators, testing with, 268
menu and choices, 265 online simulators
user agent string, 265 Cowemo, 265–266
$.mobile.showPageLoadingMsg utility finding, 265–267
method, 220 Mobile Websites 4U, 267
$.mobile.silentScroll utility method, 220 Opera Mini, 266–267
Mobilizer on/off functionality, adding, 154–155
preview tool, 21 Opera Mini online simulator, 266–267
simulator, 270 organizing information, 100
Mozilla Firefox, Modify Headers add-on, 269 orientation property
multipage template, 34–35, 42–43. See also landscape value, 195
HTML5 template; single-page template portrait value, 195
data-title attribute, 43 orientationchange event, firing, 195–196
linking from single-page template, 46
using with dialog window, 62–63
P
Paca Mobile Center remote lab, 269
N page classes, using, 184–186
name collisions, preventing, 178 page components, 33–34, 161
namespaces. See custom namespaces page data-role attribute, 35–36
- (dash) at end of, 178 page initialization
CSS selectors, 179 autoInitializePage property, 180, 182
customizing, 24–26, 178–179 delaying, 180–182
described, 178 events, 206
navbar value, using with data-role, 85 pagecreate event, 204–206
Index 279
page initialization (continued) altering default transitions, 188–189
pagecreatebefore event, 204–206 caching, 52–54
pageinit event, 204–206 changing programmatically, 210–216
page theming component, 161–162 creating in Drupal, 248–249
page titles, including in header toolbars, 76 horizontal display, 195–196
page transitions. See also webpages linking, 44
attaching event handlers, 200–201 loading, 197–199
binding event handler, 55–56 loading silently, 217–220
code sample, 56–57 loading without displaying, 217–220
defaultPageTransition property, 55 preloading, 52–54
delegate method, 201–202 referencing id value, 44
disabling, 56 as separate pages, 44
events, 200–203 single-page template, 42
fade method, 55 slide default transition, 188
flip method, 55, 57 .support properties, 260
live method, 201 ui-page-active element, 184
on method, 200–201 user agent information, 254
mobileinit event, 57–58 vertical display, 195–196
overriding default, 56 viewing in WordPress, 234
pagebeforehide, 200–203 waiting for loading, 11–12
pagebeforeshow, 200–203 pageshow event, 200–203
pagehide, 200–203 Perfecto Mobile remote lab, 269
pageshow, 200–203 PHP
pop method, 55 browser identification, 255–256
reverse, 56 /i used with regular expressions, 254–255
setting up, 55 mobile detection function, 256
slide method, 55 mobile_detect() function, 254
slidedown method, 55 OR (|) regular expression, 254–255
slideup method, 55 preg_match() function, 255
page2.html file regular expressions, 255
loading, 219 testing search strings, 255
loading silently, 218 URL redirection, 256
pagebeforehide event, 200–203 user agent information, 254
pagebeforeshow event, 200–203 pointer cursor, adding to linked lists,
pagecreate event, 204–206 107–108
pagecreatebefore event, 204–206 pop transition
pagehide event, 200–203 altering, 188
pageinit event using, 55
stage in initialization process, 204–206 using with dialog windows, 68
using with search filters, 126–128 portrait value, using with orientation
pageLoadErrorMessage property, setting, 58 property, 195
pages. See also mobile webpages pound sign (#), including in hyperlinks, 46
activeBtnClass property, 186 preloading pages, 52–54
adding to WordPress, 233–235
280 Index
Q scripts, including, 6
scroll events
queue methods lazy loading effect, 197–199
clearQueue, 13–14 scrollstart, 197
delay, 13 scrollstop, 197
dequeue, 13 SDKs (software development kits)
queue, 13 Android, 270
using, 14 benefits, 270
BlackBerry, 270
R XCode, 270
search filter bar, creating, 122–125
radio buttons, 141–145
search filter text
applying mini, 145
changing, 124
versus checkboxes, 141
custom formatted listview, 125–128
controlgroup data-role groups, 142
mobileinit event, 124–125, 130
disable method, 145
updating, 124
enable method, 145
search filters
events, 145
custom callback function, 129–130
horizontal toggle set, 143–144
customizing, 126–131
legend in fieldset, 142
defaultSearch function, 128–129
questions, 142
filterCallback option, 126
refresh method, 145
id for listview, 126–128
setting theme, 145
logging text, 129
statements, 142
pageinit event, 126–128
versus text inputs, 145
testing with searchValue, 129
ready event, using with documents, 11–12
select menus, 146–151
regular expressions
action sequence, 146
in JavaScript, 257–259
controlgroup in, 149
learning about, 255
corners option, 150
library of, 255
in fieldcontain, 147
testing, 255
formatting, 147
websites, 255
grouping, 148–149
remote labs
horizontally grouped, 149
Keynote DeviceAnywhere, 269
icon option, 150
Paca Mobile Center, 269
iconpos option, 150
Perfecto Mobile, 269
iconshadow option, 150
responsive design, considering, 196
initSelector option, 150
Roberts, Francis, 232
inline option, 150
methods, 151
S mini option, 150
nativeMenu option, 150
Save button. See also buttons
open method, 151
adding to header element, 78–80
options, 150
combining with Delete, 80
overlayTheme option, 150
Index 281
select menus (continued) slideup transition, using, 55
preventFocusZoom option, 150 special effects, applying, 12–14
shadow option, 150 split button lists. See also buttons
theme option, 150 changing default, 113
semantic HTML, 20. See also HTML creating, 112–113
elements with gear icons, 113
Sequel Pro for Mac OS spoofing user agent strings, 269
downloading, 228 step2.php page, emailAddress input, 215–216
using with Drupal, 238 Submit button, 70
using with WordPress, 228 subpages, referencing, 183
simulators, 265. See also testing with subPageUrlKey
simulators customizing, 183
finding online, 265–267 ui-page parameter, 183
Mobilizer, 270 .support method
online, 265–267 ajax feature, 260
using, 264 cors feature, 260
single-page template. See also HTML5 detecting browser features with, 259–260
template; multipage template opacity feature, 260
Ajax-based navigation, 45 properties list, 260
described, 45 submitBubbles feature, 260
dialog windows, 65 swatches. See also ThemeRoller tool
hashtags, 45–46 a-e, 158–159, 162–163
history, 45–46 applying to footer component, 162
linking to multipage template, 46 applying to header component, 162
preloading pages, 54 changing on form elements, 166
slide transition copying, 159
altering, 188 customizing, 158, 160
using, 55 defaults, 158
slidedown transition updating, 158
using, 55 using, 158–160
using with dialog windows, 68 swipe event, described, 192
sliders, 152–154 swipe event properties
creating, 152 durationThreshold, 192
disable method, 154 horizontalDistanceThreshold, 192
disabled option, 153 scrollSupressionThreshold, 192
enable method, 154 verticalDistanceThreshold, 192
events, 154 swipeleft touch event, 192
fill highlight, 153 swiperight touch event, 192
versus flip toggle switches, 155
highlight option, 153
methods, 154
T
options, 153 tap touch event, 192
refresh method, 154 taphold touch event, 192–193
trackTheme option, 153 telephone keypad, 134, 136
282 Index
testing. See also crowd testing updating, 158
on desktop, 264 using, 158–160
with desktop simulators, 270 ThemeRoller tool, 160. See also swatches
with online emulators, 268 themes
testing with simulators. See also desktop adding to WordPress, 231–232
simulators; simulators defining, 158
online emulators, 268 jQuery Mobile for Drupal, 246
options, 264 theming components. See also content
pros and cons, 263 theming; form element theming
remote labs, 269 buttons, 161–162
text inputs, 134–140 content, 163–164
alphabetical keyboard, 135–136 lists, 166–170
bind method for events, 140 page, 161–162
versus checkboxes, 145 toolbar, 161–162
clearSearchButtonText option, 139 $(this) element, using, 9–10, 12
disabled element, 139 thumbnails, adding to list items, 117–118
events, 140 toggle switch, interaction sequence, 155
initSelector option, 137 toolbar components, 33–34
methods, 139 toolbar theming component, 161–162
number patterns, 134–135 toolbars
numeric keyboard, 134 fixed, 83
options, 137–139 footers, 82
preventFocusZoom option, 138–139 fullscreen, 83–84
versus radio buttons, 145 headers, 76–77
regular and mini, 138 positioning, 83–84
setting element types, 134 updating position of, 84
telephone keypad, 134 touch events
theme option, 137 binding, 193–194
type set to number, 134 document.ready event, 193
textinput element swipe, 192
disable method, 139 swipeleft, 192
enable method, 139 swiperight, 192
theme option, 138 tap, 192
using, 137 taphold, 192–193
theme dividers, data-divider-theme, 168 .test-tap-hold class, 193–194
theme forms, creating, 165–170 transitions effects, applying to
theme swatches hyperlinks, 189
a-e, 158–159, 162–163 true/false functionality, adding, 154–155
applying to footer component, 162
applying to header component, 162
changing on form elements, 166
U
copying, 159 ui-bar-a class prefix, using, 92, 98
customizing, 158, 160 ui-block class prefix, using, 90
defaults, 158 ui-btn-icon-right class, 108
Index 283
.ui-dialog classes, using, 67 initial-scale property, 22–23
ui-grid prefix, using, 90–91 maximum-scale property, 23
ui-grid-a class prefix, using, 90 minimum-scale property, 23
ui-grid-c class prefix, using, 97 setting display with, 22
ui-li-count class, using, 115 user-scalable property, 23
ui-li-icon class, using, 118–119 width property, 22–23
ui-listview class, using, 107
ui-page-active element, 184
ui-title class, using with header
W
toolbars, 77 web hosts, choosing for WordPress, 228
url argument, using with loadPage webpages. See also mobile webpages; page
method, 218 transitions
user agent information, obtaining, 254 activeBtnClass property, 186
user agent strings, spoofing, 269 adding to WordPress, 233–235
user profile, modifying, 78–80 altering default transitions, 188–189
utility methods. See also exposed methods; caching, 52–54
methods changing programmatically, 210–216
$.mobile.activepage property, 221 creating in Drupal, 248–249
jqmData, 220 horizontal display, 195–196
jqmRemoveData, 220 linking, 44
$.mobile.base, 220 loading, 197–199
$.mobile.fixedToolbars.hide, 220 loading silently, 217–220
$.mobile.fixedToolbars.show, 220 loading without displaying, 217–220
$.mobile.hidePageLoadingMsg, 220 preloading, 52–54
$.mobile.path.isAbsoluteUrl, 220 referencing id value, 44
$.mobile.path.isRelativeUrl, 220 as separate pages, 44
$.mobile.path.isSameDomain, 220 single-page template, 42
$.mobile.path.makePathAbsolute, 220 slide default transition, 188
$.mobile.path.makeUrlAbsolute, 220 .support properties, 260
$.mobile.path.parseUrl, 220–221 ui-page-active element, 184
$.mobile.showPageLoadingMsg, 220 user agent information, 254
$.mobile.silentScroll, 220 vertical display, 195–196
using, 220–222 viewing in WordPress, 234
waiting for loading, 11–12
websites
V Cowemo online simulator, 265–266
vclick event, using bind method with, 46 Firefox Modify Headers add-on, 269
versions, minified versus source, 6 jQuery Mobile framework, 30
viewport meta tag Keynote DeviceAnywhere, 269
adding properties to, 22 Mob4Hire crowd testing, 271
described, 21 Mobile Websites 4U simulator, 267
height property, 23 mobilephoneemulator.com, 265
including in HTML5 templates, 22 Mobilizer preview tool, 21
284 Index
Mobilizer simulator, 270 DB_USER variable, 229
Mozilla Firefox Modify Headers described, 227
add-on, 269 “Hello world!” blog post, 232
online simulators, 265–267 installing, 228–230
Opera Mini online simulator, 266–267 jqm-wp database, 228
Paca Mobile Center, 269 $jqtheme value, 232
Perfecto Mobile, 269 jQuery Mobile theme, 231
regular expressions, 255 listing blog posts in, 234–235
Sequel Pro for Mac OS, 228 saving blog posts, 233
simulators, 265–267 Sequel Pro for Mac OS, 228
World Wide Web Consortium, 269 setting home page, 235
widgets, customizing, 204–206. See also viewing blog posts, 233
collapsible content widget; jQuery viewing webpages, 234
Mobile widgets web hosts, 228
WordPress. See also CMS (content wp-config.php file, 229
management system) Drupal World Wide Web Consortium, 269
adding themes to, 231–232 wp-config.php file, contents of, 229
blog posts, 233–235 WWW box model, adhering to, 259–260
changing themes, 232
creating webpages, 233–235
creating websites, 228
X
data storage, 228 XCode SDK, 270
database configuration variables, 229 XMLHttpRequest, using with webpages,
database connection, 229 36–37
database login data, 229
DB_HOST variable, 229
DB_NAME variable, 229
Y
DB_PASSWORD variable, 229 yes/no functionality, adding, 154–155
Index 285