Tải bản đầy đủ (.pdf) (247 trang)

Tài liệu jQuery Mobile Web Development Essentials docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (4.8 MB, 247 trang )

jQuery Mobile Web
Development Essentials
Learn to use the touch-optimized, cross-device,
cross-platform jQM web framework for smartphones
and tablets
Raymond Camden
Andy Matthews
BIRMINGHAM - MUMBAI
jQuery Mobile Web Development Essentials
Copyright © 2012 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the authors, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
First published: May 2012
Production Reference: 1200412
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-84951-726-3
www.packtpub.com


Cover Image by Faiz Fattohi ()
Credits
Authors
Raymond Camden
Andy Matthews
Reviewers
Md Mahmud Ahsan
Shameemah Kurzawa
M. Ali Qureshi
Joe Wu
Acquisition Editor
Usha Iyer
Lead Technical Editor
Dayan Hyames
Technical Editor
Sonali Tharwani
Project Coordinator
Sai Gamare
Proofreader
Linda Morris
Indexer
Monica Ajmera Mehta
Production Coordinators
Nilesh R. Mohite
Prachali Bhiwandkar
Cover Work
Nilesh R. Mohite
About the Authors
Raymond Camden is a Developer Evangelist for Adobe focusing on web
standards and mobile development. He is a contributing author to numerous

technical books including the best selling ColdFusion Web Application Construction
Kit, published by Adobe Press. He has spoken at conferences around the world
and maintains many popular ColdFusion community websites. He is the
manager of www.RIAForge.org, www.CFLib.org, and writes at his blog
www.raymondcamden.com. Raymond is happily married and a proud father
to three kids and is somewhat of a Star Wars nut.
I'd like to thank everyone on the jQuery and jQuery Mobile teams
for making tools that have changed my life. Without your hard work
and dedication, the web would be less awesome. Thank you Andy,
for coming on board and helping to make this book better.
Andy Matthews has been working as a web and application developer for 13
years, with an experience in a wide range of industries, and has a skill set which
includes graphic design, programming, business strategy and planning, and
marketing. Throughout his career he has been privileged to work on projects
which interfaced with industry giants such as Craigslist, written code that allowed
Enterprise level sales teams to quickly and efciently build presentations for their
clients. He stays up-to-date with current trends in the marketplace by helping
previous employers transition to newer, more effective, coding habits and standards.
He is a frequent speaker at conferences around the country. He has also developed
software for the open source community, and he currently works for a social
networking startup Goba.mobi in Nashville, TN.
I'd like to thank my wife Jaime, and my children Noelle, Evan, and
Mason for their patience and grace in letting me pursue my passion.
Most of all, thank you God for giving me the desire to learn, the
ability to pick things up quickly, and the perseverance to apply the
knowledge I've gained throughout the years.
About the Reviewers
Md Mahmud Ahsan has been developing and leading some medium to large
web applications for the past six years. He has worked with a number of PHP
frameworks (Zend, CodeIgniter) and generally likes working with an MVC design

pattern. His experience ranges from developing web applications from scratch, as
well as modifying and adding functionality to existing custom in-house systems,
open source applications, and commercial applications. He graduated in Computer
Science and Engineering, and is a PHP5 Zend Certied Engineer. He is also an
expert in iPhone applications development and has in depth working knowledge
in Objective C, C, C++, Cocos2D, Box2D, and Xcode. Apart from his full time job,
he maintains a blog at . He lives in Bangladesh with his
wife Jinat Jahan.
Currently, he is self employed and has been developing iPhone and iPad
applications, which he publishes through his own site
.
Besides this, he is a part time freelancer and works on LAMP based web
applications development.
He was a technical reviewer for the following books published by Packt Publishing:
• Zend Framework 1.8 Web Application Development Book
• PHP jQuery Cookbook
• jQuery UI themes
• Android 3.0 Application Development Cookbook
I'm very grateful to my father who brought a computer for me
in 2001, since then I have loved programming and work in
various technologies.
Shameemah Kurzawa started programming when she was at high school.
Being motivated to be a System Analyst, she pursued both undergraduate
and postgraduate studies in Business Information Systems and Software
Engineering respectively.
She has been working as a Web Developer/Analyst for the past six years; she
has worked in the past for Australia's renowned broadcasting company SBS
and has freelanced for her own company since 2010. Besides work she enjoys
spending time with her family, traveling, and cooking. She likes to read and
try new web technologies.

She has previously reviewed jQuery UI themes and PHP jQuery Cookbook for
Packt Publishing.
I would like to thank my husband and the Packt team for their
support and understanding in helping me review this book.
M. Ali Qureshi is based in Lahore, Pakistan. He has developed a comprehensive
understanding of web development processes having worked in the capacity of
Web Designer, Frontend developer, PHP Developer, Flash ActionScript Developer,
Software Engineer, and Project Manager in the last 12 years designing and
developing creative, interactive and usable web solutions, that get high rankings
in search engines and drive qualied trafc to websites, making them a successful
technology investment.
He has done a Masters in Economics and Computer Sciences. Running along Lahore
canal early in the morning, watching good movies and listening to music, working
out at the gym, reading books, discussing politics, and an occasional stroll in
Lawrence Garden, Lahore are a few things that Ali mostly enjoys.
When not working, he spends his time blogging and exploring new technologies.
Ali is an avid sports fan and likes watching Cricket, especially Pakistan and Australia
which are his favorite teams.
Joe Wu is a Senior PHP Web Developer and has more than four years of commercial
experience to date.
Joe is always enthusiastic about exploring new ideas, technologies and opportunities
that arise. He has a wide range of skills, specializing primarily in PHP, CodeIgniter
PHP Framework, MySQL, JQuery, HTML, and CSS. Joe's skills and experiences
further extends out to various other technologies and tools such as Subversion,
Microsoft CRM, SOAP, Bash Scripting, and Symfony PHP Framework.
Joe is also a professional Badminton player, achieving the highest ranking of 59 in
the world in singles and top ranking in Australasia in 2010.
If you would like to get in touch with Joe to discuss any opportunities please do not
hesitate to visit his personal website:
/>www.PacktPub.com

Support les, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support les and downloads related
to your book.
Did you know that Packt offers eBook versions of every book published, with PDF
and ePub les available? You can upgrade to the eBook version at
www.PacktPub.
com
and as a print book customer, you are entitled to a discount on the eBook copy.
Get in touch with us at for more details.
At
www.PacktPub.com, you can also read a collection of free technical articles, sign
up for a range of free newsletters and receive exclusive discounts and offers on
Packt books and eBooks.

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can access, read and search across Packt's entire library of books.
Why Subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print and bookmark content
• On demand and accessible via web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view nine entirely free books. Simply use your login credentials
for immediate access.

To my wife Jeanne. Thank you for always being there. Thank you for making me feel like I
could do this. Thank you being strong when I'm weak. Thank you for everything.
-Raymond Camden

Table of Contents

Preface 1
Chapter 1: Preparing your First jQuery Mobile Project 11
Important preliminary points 11
Building an HTML page 11
Getting jQuery Mobile 13
Implementing jQuery Mobile 14
Working with data attributes 16
Summary 18
Chapter 2: Working with jQuery Mobile Pages 19
Important preliminary points 19
Adding multiple pages to one le 20
jQuery Mobile, links, and you 22
Working with multiple les 23
jQuery Mobile and URLs 26
Additional customization 26
Page titles 27
Prefetching content 28
Changing page transitions 28
Summary 29
Chapter 3: Enhancing Pages with Headers, Footers, and Toolbars 31
Important preliminary points 31
Adding headers 31
Icon sneak peak 34
Working with back buttons 34
Working with footers 36
Creating xed and full screen headers and footers 38
Full screen positioning 39
Working with navigation bars 40
Persisting navigation bar footers across multiple pages 42
Table of Contents

[ ii ]
Summary 44
Chapter 4: Working with Lists 45
Creating lists 45
Working with list feature 50
Creating Inset lists 51
Creating list dividers 52
Creating lists with count bubbles 53
Using thumbnails and icons 54
Creating Split Button lists 56
Using a search lter 57
Summary 58
Chapter 5: Getting Practical – Building a Simple Hotel Mobile Site 59
Welcome to Hotel Camden 59
The home page 60
Finding the hotel 62
Listing the hotel rooms 65
Contacting the hotel 68
Summary 70
Chapter 6: Working with Forms and jQuery Mobile 71
Before you begin 71
What jQuery Mobile does with forms 72
Working with radio buttons and checkboxes 76
Working with select menus 79
Search, toggle, and slider elds 82
Search elds 83
Flip toggle elds 83
Slider elds 84
Using native form controls 85
Working with "mini" elds 85

Summary 86
Chapter 7: Creating Modal Dialogs, Grids, and Collapsible Blocks 87
Creating dialogs 87
Laying out content with grids 91
Working with collapsible content 97
Summary 102
Chapter 8: jQuery Mobile Conguration, Utilities,
and JavaScript methods 103
Conguring jQuery Mobile 103
Using jQuery Mobile utilities 109
Page methods and utilities 109
Table of Contents
[ iii ]
Path and URL related utilities 111
Miscellaneous utilities 115
jQuery widget and form utilities 115
Summary 119
Chapter 9: Working with Events 121
Working with physical events 121
Handling page events 129
What about $(document).ready? 133
Creating a real example 133
Summary 136
Chapter 10: Moving further with the Notekeeper
Mobile Application 137
What is a mobile application? 137
Designing your rst mobile application 138
Listing out the requirements 138
Building your wireframes 139
Designing the add note wireframe 139

Display notes wireframe 140
View note/delete button wireframe 140
Writing the HTML 141
Adding functionality with JavaScript 143
Storing Notekeeper data 146
Using localStorage 146
Effective use of boilerplates 148
Building the Add Note feature 148
Adding bindings 148
Collecting and storing the data 150
Building the Display Notes feature 151
Dynamically adding notes to our listview 153
Viewing a note 154
Using the Live function 154
Dynamically creating a new page 155
Deleting a note 157
Summary 158
Chapter 11: Enhancing jQuery Mobile 159
What's possible? 159
The visual building blocks of jQuery Mobile 160
Border-radius 161
Applying drop shadows 162
Using text-shadow 163
Using box-shadow 164
CSS gradients 165
Table of Contents
[ iv ]
The basics of jQuery Mobile theming 168
Bars (.ui-bar-?) 169
Content blocks (.ui-body-?) 169

Buttons and listviews (.ui-btn-?) 170
Mixing and matching swatches 170
Site-wide active state 171
Default icons 172
Creating and using a custom theme 172
What's ThemeRoller? 173
Using ThemeRoller 173
Preview 175
Colors 175
Inspector 176
Tools 177
Creating a theme for Notekeeper 178
Exporting your theme 181
Creating and using custom icons 183
CSS Sprites 183
Designing your rst icon 185
High and low resolution 187
Updating the Notekeeper app 188
Adding our custom theme 188
Adding our custom icon 189
Summary 190
Chapter 12: Creating Native Applications 191
HTML as a native application 191
Working with PhoneGap 192
Adding PhoneGap functionality 199
Summary 203
Chapter 13: Becoming an expert - Build an RSS
Reader application 205
RSS Reader – the application 205
Creating the RSS Reader Application 208

The displayFeeds function 210
Storing our feeds 211
Adding an RSS feed 212
Viewing a feed 214
Creating the entry view 216
Going further 218
Summary 218
Index 219
Preface
What is jQuery Mobile?
On August 11, 2010, nearly two years ago, John Resig (creator of jQuery) announced
the jQuery Mobile project. While focused on the UI framework, it was also a
recognition of jQuery itself as a tool for mobile sites and that work would be done
to the core framework itself, to make it work better on devices. Release after release,
the jQuery Mobile project evolved into a powerful framework encompassing more
platforms, more features, and better performance with every update.
But what do we mean when we say a UI framework? What does it mean for developers
and designers? jQuery Mobile provides a way to turn regular HTML (and CSS) into
mobile friendly sites. As you will see soon in the rst chapter, you can take a regular
HTML page, add in the required bits for jQuery Mobile (essentially ve lines of
HTML), and nd your page transformed into a mobile-friendly version instantly.
Unlike other frameworks, jQuery Mobile is focused on HTML. In fact, for a
framework tied to jQuery, you can do a heck of a lot of work without writing one
line of JavaScript. It's a powerful, practical way of creating mobile websites that
any existing HTML developer can pick up and adapt within a few hours. Compare
this to other frameworks, such as Sencha Touch. Sencha Touch is also a powerful
framework, but its approach is radically different, using JavaScript to help dene
and layout pages. jQuery Mobile is much friendlier to people who are more familiar
with HTML, as opposed to JavaScript. jQuery Mobile is touch friendly, which will
make sense to anyone who has used a smart phone and struggled to click the exact

right spot on a website with tiny text and hard to spot links. It will make sense to
anyone who accidentally clicked on a Reset button instead of Submit. jQuery Mobile
will enhance your content to help solve these issues. Regular buttons become large,
fat, and easy to hit buttons. Links can be turned into list based navigation systems.
Content can be split into virtual pages with smooth transitions. You will be surprised
just how jQuery Mobile works without writing much code at all.
Preface
[ 2 ]
jQuery Mobile has some very big sponsors. They include Nokia, Blackberry, Adobe,
and other large companies. These companies have put in money, hardware, and
developer resources to help ensure the success of the project:
What's the cost?
Ah, the million dollar question. Luckily this one is easy to answer: nothing. jQuery
Mobile, like jQuery itself, is completely free to use for any purpose. Not only that, it's
completely open source. Don't like how something works? You can change it. Want
something not supported by the framework? You can add it. To be fair, digging deep
into the code base is probably something most folks will not be comfortable doing.
However, the fact that you can if you need to, and the fact that other people can,
leads to a product that will be open to development by the community at large.
Preface
[ 3 ]
What do you need to know?
Finally, along with not paying a dime to get, and work with, jQuery Mobile, the
best thing is that you probably already have all the skills necessary to work with
the framework. As you will see in the upcoming chapters, jQuery Mobile is an
HTML based framework. If you know HTML, even just simple HTML, you can use
the jQuery Mobile framework. Knowledge of CSS and JavaScript is a plus, but not
entirely required. (While jQuery Mobile uses a lot of CSS and JavaScript behind the
scenes, you don't actually have to write any of this yourself!)
What about native apps?

jQuery Mobile does not create native applications. You'll see later in the book how
you can combine jQuery Mobile with wrapper technologies such as PhoneGap to
create native apps but, in general, jQuery Mobile is for building websites. The
question on whether to develop a website or a mobile app is not something this book
can answer. You need to look at your business needs and see what will satisfy them.
Because we are not building mobile apps themselves, you do not have to worry
about setting up any accounts with Google or Apple, or paying any fees for the
marketplace. Any user with a mobile device that includes a browser will be able to
view your mobile-optimized sites.
Again – if you want to develop true mobile apps with jQuery Mobile, it's
denitely an option.
Help!
While we'd like to think that this book will cover every single possible topic you
would need for all your jQuery Mobile needs, most likely there will be things we
can't cover. If you need help, there are a couple of places you can try.
First, the jQuery Mobile docs (
cover
syntax, features, and development in general, much like this book. While the
material may cover some of the same ground, if you nd something confusing here,
try the ofcial docs. Sometimes a second explanation can really help.
Second, the jQuery Mobile forum (

is an open ended discussion list for jQuery Mobile topics. This is the perfect place
to ask questions. Also, it's a good place to learn about problems other people are
having. You may even be able to help them. One of the best ways to learn a new
topic is by helping others.
Preface
[ 4 ]
Examples
Want to see jQuery Mobile in action? There's a site for that. JQM Gallery

( is a collection of sites submitted by users,
built using jQuery Mobile. Not surprisingly, this website too uses jQuery Mobile,
which makes it yet another way to sample jQuery Mobile:
Preface
[ 5 ]
What this book covers
Chapter 1, Preparing your First jQuery Mobile Project, works you through your rst
jQuery Mobile project. It details what must be added to your project's directory
and source code.
Chapter 2, Working with jQuery Mobile Pages, continues the work in the previous
chapter and introduces the concept of jQuery Mobile pages.
Chapter 3, Enhancing Pages with Headers, Footers, and Toolbars, explains how to
enhance your pages with nicely formatted headers and footers.
Chapter 4, Working with Lists, describes how to create jQuery Mobile list views.
These are mobile optimized lists which are especially great for navigation.
Chapter 5, Getting Practical – Building a Simple Hotel Mobile Site, walks you through
creating your rst "real" (albeit simple) jQuery Mobile application.
Chapter 6, Working with Forms and jQuery Mobile, explains the process of using jQuery
Mobile optimized forms. Layout and special form features are covered in detail.
Chapter 7, Creating Modal Dialogs, Grids, and Collapsible Blocks, walks you through
special jQuery Mobile user interface items for creating grid based layouts, dialogs,
and collapsible content areas.
Chapter 8, jQuery Mobile Conguration, Utilities, and JavaScript methods, describes the
various JavaScript-based utilities your code may have need of.
Chapter 9, Working with Events, details the events thrown by various jQuery
Mobile-related features, like pages loading and unloading.
Chapter 10, Moving Further with the Notekeeper Mobile Application, walks you
through the process of creating another website, an HTML5-enhanced note
taking application.
Chapter 11, Enhancing jQuery Mobile, demonstrates how to change the default

appearance of your jQuery Mobile sites by selecting and creating unique themes.
Chapter 12, Creating Native Applications, takes what you've learned previously
and shows how to use the open source PhoneGap project to create real
native applications.
Chapter 13, Becoming an expert Build an RSS Reader application, expands upon the
previous chapter by creating an application that lets you add and read RSS feeds
on mobile devices.
Preface
[ 6 ]
What you need for this book
Nothing! Technically you need a computer, and a browser as well, but jQuery
Mobile is built with HTML, CSS, and JavaScript. No IDE (Integrated Development
Environment) or special tool will be required to work with the framework. If you've
got any editor on your system (and all operating systems include a free editor of
some sort), you can develop with jQuery Mobile.
There are good IDEs out there that can help you be more productive. For example,
Adobe Dreamweaver CS 5.5 includes native support for jQuery Mobile with code
assist and device previews:
At the end of the day, you can develop with jQuery Mobile for free. It's zero cost to
you to download, develop, and publish jQuery Mobile sites.
Who this book is for
This book is for anyone looking to embrace mobile development and expand their
skill set beyond the desktop.
Preface
[ 7 ]
Conventions
In this book, you will nd a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.
Code words in text are shown as follows: "Notice the new

data-title tag added
to the
div tag."
A block of code is set as follows:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-
scale=1">
<title>Multi Page Example</title>
New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes for example, appear in the text like this: "Imagine
our Megacorp page. It's got three pages, but the Products page is a separate
HTML le."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or may have disliked. Reader feedback is important for us
to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to
,
and mention the book title through the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide on
www.packtpub.com/authors.
Preface
[ 8 ]
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.

Downloading the example code
This book contains many code samples. You are not expected to type them in. You
should not type them all in. Rather, you should download them from the public
Github repository setup for the book: />jQuery-Mobile-Book
. The Github repository will be updated as typos and other
mistakes are found in the book. Therefore, it is possible the code may not match
exactly the text in the book.
If you are not familiar with Github, then simply click the Downloads tab and then
either Download as zip or Download as tar.gz to quickly get an archived collection
of all the les.
You should extract these les onto a local web server. If you do not have one
installed, we recommend installing Apache (
Apache
works on all platforms, is free, and is typically easy to install. Once extracted, you
can edit these les, view them in your browser, or copy them as a starting point for
your own projects.
You can also download the example code les for all Packt books you have
purchased from your account at
. If you purchased this
book elsewhere, you can visit and register
to have the les e-mailed directly to you.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you nd a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you would report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you nd any errata, please report them by visiting ktpub.
com/support
, selecting your book, clicking on the errata submission form link, and
entering the details of your errata. Once your errata are veried, your submission

will be accepted and the errata will be uploaded to our website, or added to any list
of existing errata, under the Errata section of that title.

×