Building iPhone Apps with HTML, CSS, and
JavaScript
Building iPhone Apps with HTML,
CSS, and JavaScript
Jonathan Stark
Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo
Building iPhone Apps with HTML, CSS, and JavaScript
by Jonathan Stark
Copyright © 2010 Jonathan Stark. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions
are also available for most titles (http://my.safaribooksonline.com). For more information, contact our
corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com.
Editor: Brian Jepson
Production Editor: Sumita Mukherji
Copyeditor: Emily Quill
Proofreader: Sada Preisch
Indexer: Fred Brown
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Robert Romano
Printing History:
January 2010: First Edition.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of
O’Reilly Media, Inc. Building iPhone Apps with HTML, CSS, and JavaScript, the image of a bluebird, and
related trade dress are trademarks of O’Reilly Media, Inc.
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 O’Reilly Media, Inc., was aware of a
trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author assume
no responsibility for errors or omissions, or for damages resulting from the use of the information con-
tained herein.
This work is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0
United States License.
TM
This book uses RepKover™, a durable and flexible lay-flat binding.
ISBN: 978-0-596-80578-4
[M]
1262957633
To Erica—and that little jumping bean in her
tummy.
Table of Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
1. Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Web Apps Versus Native Apps 1
What Is a Web App? 1
What Is a Native App? 1
Pros and Cons 2
Which Approach Is Right for You? 2
Web Programming Crash Course 3
Intro to HTML 3
Intro to CSS 6
Intro to JavaScript 9
2. Basic iPhone Styling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
First Steps 14
Preparing a Separate iPhone Stylesheet 16
Controlling the Page Scaling 17
Adding the iPhone CSS 19
Adding the iPhone Look and Feel 21
Adding Basic Behavior with jQuery 23
What You’ve Learned 28
3. Advanced iPhone Styling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Adding a Touch of Ajax 29
Traffic Cop 29
Simple Bells and Whistles 34
Roll Your Own Back Button 40
Adding an Icon to the Home Screen 46
Full Screen Mode 48
Changing the Status Bar 48
Providing a Custom Startup Graphic 49
vii
What You’ve Learned 50
4. Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
With a Little Help from Our Friend 51
Sliding Home 51
Adding the Dates Panel 55
Adding the Date Panel 56
Adding the New Entry Panel 58
Adding the Settings Panel 60
Putting It All Together 62
Customizing jQTouch 64
What You’ve Learned 67
5. Client-Side Data Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
localStorage and sessionStorage 69
Saving User Settings to localStorage 70
Saving the Selected Date to sessionStorage 73
Client-Side Database 74
Creating a Database 75
Inserting Rows 78
Selecting Rows and Handling Result Sets 82
Deleting Rows 86
What You’ve Learned 89
6. Going Offline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
The Basics of the Offline Application Cache 91
Online Whitelist and Fallback Options 94
Creating a Dynamic Manifest File 98
Debugging 102
The JavaScript Console 103
The Application Cache Database 107
What You’ve Learned 113
7. Going Native . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Intro to PhoneGap 115
Using the Screen’s Full Height 121
Customizing the Title and Icon 123
Creating a Startup Screen 130
Installing Your App on the iPhone 131
Controlling the iPhone with JavaScript 136
Beep, Vibrate, and Alert 136
Geolocation 140
Accelerometer 146
viii | Table of Contents
What You’ve Learned 150
8. Submitting Your App to iTunes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Creating an iPhone Distribution Provisioning Profile 151
Installing the iPhone Distribution Provisioning Profile 153
Renaming the Project 155
Prepare the Application Binary 156
Submit Your App 157
While You Wait 159
Further Reading 159
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Table of Contents | ix
Preface
Like millions of people, I fell in love with my iPhone immediately. Initially, web apps
were the only way to get a custom app on the device, which was fine by me because
I’m a web developer. Months later when the App Store was announced, I was jacked.
I ran out and bought every Objective-C book on the market. Some of my web apps
were already somewhat popular, and I figured I’d just rewrite them as native apps, put
them in the App Store, and ride off into the sunset on a big, galloping pile of money.
Disillusionment followed. I found it difficult to learn Objective-C, and I was turned off
by the fact that the language was of little use outside of Mac programming. Xcode and
Interface Builder were pretty slick, but they weren’t my normal authoring environment
and I found them hard to get accustomed to. I was infuriated by the hoops I had to
jump through just to set up my app and iPhone for testing. The process of getting the
app into the App Store was even more byzantine. After a week or two of struggling with
these variables, I found myself wondering why I was going to all the trouble. After all,
my web apps were already available worldwide—why did I care about being in the App
Store?
On top of all this, Apple can—and does—reject apps. This is certainly their prerogative,
and maybe they have good reasons. However, from the outside, it seems capricious and
arbitrary. Put yourself in these shoes (based on a true story, BTW): you spend about
100 hours learning Objective-C. You spend another 100 hours or so writing a native
iPhone app. Eventually, your app is ready for prime time and you successfully navigate
the gauntlet that is the App Store submission process. What happens next?
You wait. And wait. And wait some more. We are talking weeks, and sometimes
months. Finally you hear back! And...your app is rejected. Now what? You have noth-
ing to show for your effort. The bubble.
But wait, it can get worse. Let’s say you do get your app approved. Hundreds or maybe
thousands of people download your app. You haven’t received any money yet, but you
are on cloud nine. Then, the bug reports start coming in. You locate and fix the bug in
minutes, resubmit your app to iTunes, and wait for Apple to approve the revision. And
wait. And wait some more. Angry customers are giving you horrible reviews in the App
Store. Your sales are tanking. And still you wait. You consider offering a refund to the
xi
angry customers, but there’s no way to do that through the App Store. So you are
basically forced to sit there watching your ratings crash even though the bug was fixed
days or weeks ago.
Sure, this story is based on the experience of one developer. Maybe it’s an edge case
and the actual data doesn’t bear out my thesis. But the problem remains: we developers
have no access to Apple’s data, or the real details of the App Store approval process.
Until that changes, building a native app with Objective-C is a risky proposition.
Fortunately, there is an alternative. You can build a web app using open source,
standards-based web technologies, release it as a web app, and debug and test it under
load with real users. Once you are ready to rock, you can use PhoneGap to convert
your web app to a native iPhone app and submit it to the App Store. If it’s ultimately
rejected, you aren’t dead in your tracks because you can still offer the web app. If it’s
approved, great! You can then start adding features that enhance your web app by
taking advantage of the unique hardware features available on the device. Sounds like
the best of both worlds, right?
Who Should Read This Book
I’m going to assume that you have some basic experience reading and writing HTML,
CSS, and JavaScript (jQuery in particular). I will be including some basic SQL code in
Chapters 5 and 6, so a passing familiarity with SQL syntax would be helpful but is not
required.
What You Need to Use This Book
This book is going to avoid the iPhone SDK wherever possible. All you’ll need to follow
along with the vast majority of examples is a text editor and the most recent version of
Safari (or better yet, WebKit, which is a more cutting-edge version of Safari that’s
available for both Mac and Windows at http://webkit.org). You do need a Mac for the
PhoneGap material in Chapter 7, where I explain how to convert your web app into a
native app that you can submit to the App Store.
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Used for program listings, as well as within paragraphs to refer to program elements
such as variable or function names, databases, data types, environment variables,
statements, and keywords.
xii | Preface
Constant width bold
Shows commands or other text that should be typed literally by the user and for
emphasis within code listings.
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter-
mined by context.
This icon signifies a tip, suggestion, or general note.
This icon indicates a warning or caution.
Using Code Examples
This book is here to help you get your job done. In general, you may use the code in
this book in your programs and documentation. You do not need to contact us for
permission unless you’re reproducing a significant portion of the code. For example,
writing a program that uses several chunks of code from this book does not require
permission. Selling or distributing a CD-ROM of examples from O’Reilly books does
require permission. Answering a question by citing this book and quoting example
code does not require permission. Incorporating a significant amount of example code
from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the
title, author, publisher, and ISBN. For example: “Building iPhone Apps with
HTML, CSS, and JavaScript by Jonathan Stark. Copyright 2010 Jonathan Stark,
978-0-596-80578-4.”
If you feel your use of code examples falls outside fair use or the permission given above,
feel free to contact us at permissions@oreilly.com.
Safari® Books Online
Safari Books Online is an on-demand digital library that lets you easily
search over 7,500 technology and creative reference books and videos to
find the answers you need quickly.
With a subscription, you can read any page and watch any video from our library online.
Read books on your cell phone and mobile devices. Access new titles before they are
available for print, and get exclusive access to manuscripts in development and post
Preface | xiii
feedback for the authors. Copy and paste code samples, organize your favorites, down-
load chapters, bookmark key sections, create notes, print out pages, and benefit from
tons of other time-saving features.
O’Reilly Media has uploaded this book to the Safari Books Online service. To have full
digital access to this book and others on similar topics from O’Reilly and other pub-
lishers, sign up for free at http://my.safaribooksonline.com.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at:
http://www.oreilly.com/catalog/9780596805784/
To comment or ask technical questions about this book, send email to:
bookquestions@oreilly.com
For more information about our books, conferences, Resource Centers, and the
O’Reilly Network, see our website at:
http://www.oreilly.com
Acknowledgments
Writing a book is a team effort. My heartfelt thanks go out to the following people for
their generous contributions.
Tim O’Reilly, Brian Jepson, and the rest of the gang at ORM for making the experience
of writing this book so rewarding and educational.
Jack Templin, Providence Geeks, and RI Nexus for introducing me to the thriving tech
scene in my own hometown. This book wouldn’t exist if it weren’t for Providence
Geeks.
David Kandeda for his wonderfully obsessive pursuit of beauty. Whether it’s a bit of
code, or a user interface animation, he can’t sleep until it’s perfect, and I love that.
Brian LeRoux, Brock Whitten, Rob Ellis, and the rest of the gang at Nitobi for creating
and continuing to support PhoneGap.
xiv | Preface
Brian Fling for broadening my view of mobile beyond just the latest and greatest hard-
ware. Brian knows mobile from back in the day; he’s a wonderful writer, and on top
of that, a very generous guy.
PPK, John Gruber, John Allsopp, and John Resig for their contributions to and support
of the underlying technologies that made this book possible.
Garrett Murray, Brian LeRoux, and the swarm of folks who generously posted com-
ments and questions on the OFPS site for this book. Your feedback was very helpful
and much appreciated.
Kazu, Chuckie, Janice, Chris, and the rest of the gang at Haruki for being so accom-
modating while I endlessly typed away at the high top by the door.
My wonderful family, friends, and clients for being understanding and supportive while
I was chained to the keyboard.
And finally, Erica. You make everything possible. I love you!
Preface | xv
CHAPTER 1
Getting Started
Before we dive in and start building applications for the iPhone, I’d like to quickly
establish the playing field. In this chapter, I’ll define key terms, compare the pros and
cons of the two most common development approaches, and present a crash course in
the three core web technologies that are used in this book.
Web Apps Versus Native Apps
First, I’ll define what I mean by “web app” and “native app” and consider the pros and
cons of each.
What Is a Web App?
To me, a web app is basically a website that is specifically optimized for the iPhone.
The site can be anything from a standard small-business brochure site to a mortgage
calculator to a daily calorie tracker—the content is irrelevant. The defining character-
istics of a web app are that the user interface is built with web-standard technologies,
it is available at a URL (public, private, or behind a login), and it is optimized for the
specifics of the iPhone. A web app is not installed on the phone, is not available in the
iTunes App Store, and is not written with Objective-C.
What Is a Native App?
In contrast, native apps are installed on the iPhone, have access to the hardware (speak-
ers, accelerometer, camera, etc.), and are written with Objective-C. The defining char-
acteristic of a native app, however, is that it’s available in the iTunes App Store—a
feature that has captured the imagination of hordes of software entrepreneurs world-
wide, myself included.
1
Pros and Cons
Different applications have different requirements. Some apps are a better fit with web
technologies than others. Knowing the pros and cons of each approach will help you
make the right decision about which path is appropriate for your situation.
Here are the pros of native app development:
• Millions of registered credit card owners are one click away.
• Xcode, Interface Builder, and the Cocoa Touch framework constitute a pretty
sweet development environment.
• You can access all the cool hardware features of the device.
Here are the cons of native app development:
• You have to pay to become an Apple developer.
• You are at the mercy of the Apple approval process.
• You have to develop using Objective-C.
• You have to develop on a Mac.
• You can’t release bug fixes in a timely fashion.
• The development cycle is slow, and the testing cycle is constrained by the App
Store’s limitations.
Here are the pros of web app development:
• Web developers can use their current authoring tools.
• You can use your current web design and development skills.
• You are not limited to developing on the Mac OS.
• Your app will run on any device that has a web browser.
• You can fix bugs in real time.
• The development cycle is fast.
Here are the cons of web app development:
• You cannot access the all cool hardware features of the phone.
• You have to roll your own payment system if you want to charge for the app.
• It can be difficult to achieve sophisticated UI effects.
Which Approach Is Right for You?
Here’s where it gets exciting. The always-online nature of the iPhone creates an envi-
ronment in which the lines between a web app and a native app get blurry. There are
even some little-known features of the iPhone that allow you to take a web app offline
if you want (see Chapter 6). What’s more, several third-party projects—of which
2 | Chapter 1: Getting Started
v@v
Text Box
Download at WoweBook.com
PhoneGap is the most notable—are actively developing solutions that allow web de-
velopers to take a web app and package it as a native app for the iPhone and other
mobile platforms.
For me, this is the perfect blend. I can write in my native language, release a product
as a pure web app (for the iPhone and any other devices that have a modern browser)
without going through Apple’s approval process, and use the same codebase to create
an enhanced native version that can access the device hardware and potentially be sold
in the App Store. And if Apple rejects it? No big deal, because I still have my online
version. I can keep working on the native version while customers use the web app.
Web Programming Crash Course
The three main technologies we are going to use to build web apps are HTML, CSS,
and JavaScript. I’d like to quickly cover each to make sure we’re all on the same page
before plowing into the fancy stuff.
Intro to HTML
When you’re browsing the Web, the pages that you are viewing are just text documents
sitting on someone else’s computer. The text in a typical web page is wrapped in HTML
tags, which tell your browser about the structure of the document. With this informa-
tion, the browser can decide how to display the information in a way that makes sense.
Consider the web page snippet shown in Example 1-1. On the first line, the string Hi
there! is wrapped in a pair of h1 tags. (Notice that the open tag and the close tag are
slightly different: the close tag has a slash as the second character, while the open tag
does not.)
Wrapping some text in h1 tags tells the browser that the words enclose