Head First Mobile Web
Head First Mobile Web
info
www.it-ebooks.info
www.it-ebooks.info
Advance Praise for Head First Mobile Web
“If you have been considering buying a book about mobile development that is cross‑browser and
cross‑vendor, you should stop right now and buy Head First Mobile Web. It’s written by amazingly smart
people [who] have great experience on mobile and don’t stop at one platform, but work on all of them.
Many developers spend days arguing [whether] they should go native or web. This book smoothly
goes from introductory topics to advanced ones, giving you all the needed information to create
exciting content for mobile.”
— Andrea Trasatti, leader of the DeviceAtlas project and cocreator of
the WURFL repository of wireless device capability information
“A pragmatic introduction to the chaotic world of mobile web development as it is today, with a
glimpse of how we can and should approach it for tomorrow. Head First Mobile Web successfully
presents practical techniques all readers can use immediately, while giving plenty of foundation and
resources for more experienced developers to build upon.”
— Stephen Hay, web designer, developer, speaker, and
cofounder of the Mobilism conference
“Hands‑on from the get‑go, Head First Mobile Web provides an excellent introduction to the challenges
and opportunities available when exploring the next chapter in web design.”
— Bryan and Stephanie Rieger, founders of yiibu.com
www.it-ebooks.info
Praise for other Head First books
“Head First Object-Oriented Analysis and Design is a refreshing look at subject of OOAD. What sets this book
apart is its focus on learning. The authors have made the content of OOAD accessible [and] usable for
the practitioner.”
— Ivar Jacobson, Ivar Jacobson Consulting
“I just finished reading HF OOA&D, and I loved it! The thing I liked most about this book was its focus
on why we do OOA&D—to write great software!”
— Kyle Brown, Distinguished Engineer, IBM
“Hidden behind the funny pictures and crazy fonts is a serious, intelligent, extremely well‑crafted
presentation of OO analysis and design. As I read the book, I felt like I was looking over the shoulder of
an expert designer who was explaining to me what issues were important at each step, and why.”
— Edward Sciore, Associate Professor, Computer Science Department,
Boston College
“All in all, Head First Software Development is a great resource for anyone wanting to formalize their
programming skills in a way that constantly engages the reader on many different levels.”
— Andy Hudson, Linux Format
“If you’re a new software developer, Head First Software Development will get you started off on the right foot.
And if you’re an experienced (read: long‑time) developer, don’t be so quick to dismiss this.…”
— Thomas Duff, Duffbert’s Random Musings
“There’s something in Head First Java for everyone. Visual learners, kinesthetic learners, everyone can
learn from this book. Visual aids make things easier to remember, and the book is written in a very
accessible style—very different from most Java manuals.… Head First Java is a valuable book. I can
see the Head First books used in the classroom, whether in high schools or adult ed classes. And I will
definitely be referring back to this book, and referring others to it as well.”
— Warren Kelly, Blogcritics.org, March 2006
“Rather than textbook‑style learning, Head First iPhone and iPad Development brings a humorous, engaging,
and even enjoyable approach to learning iOS development. With coverage of key technologies including
core data, and even crucial aspects such as interface design, the content is aptly chosen and top‑notch.
Where else could you witness a fireside chat between a UIWebView and UITextField!”
— Sean Murphy, iOS designer and developer
www.it-ebooks.info
Praise for other Head First books
“Another nice thing about Head First Java, Second Edition, is that it whets the appetite for more. With
later coverage of more advanced topics such as Swing and RMI, you just can’t wait to dive into those
APIs and code that flawless, 100,000‑line program on java.net that will bring you fame and venture‑
capital fortune. There’s also a great deal of material, and even some best practices, on networking and
threads—my own weak spot. In this case, I couldn’t help but crack up a little when the authors use
a 1950s telephone operator—yeah, you got it, that lady with a beehive hairdo that manually hooks in
patch lines—as an analogy for TCP/IP ports…you really should go to the bookstore and thumb through
Head First Java, Second Edition. Even if you already know Java, you may pick up a thing or two. And if
not, just thumbing through the pages is a great deal of fun.”
— Robert Eckstein, Java.sun.com
“Of course it’s not the range of material that makes Head First Java stand out, it’s the style and approach.
This book is about as far removed from a computer science textbook or technical manual as you can get.
The use of cartoons, quizzes, fridge magnets (yep, fridge magnets…). And, in place of the usual kind of
reader exercises, you are asked to pretend to be the compiler and compile the code, or perhaps to piece
some code together by filling in the blanks or…you get the picture.… The first edition of this book was
one of our recommended titles for those new to Java and objects. This new edition doesn’t disappoint
and rightfully steps into the shoes of its predecessor. If you are one of those people who falls asleep with
a traditional computer book, then this one is likely to keep you awake and learning.”
— TechBookReport.com
“Head First Web Design is your ticket to mastering all of these complex topics, and understanding what’s
really going on in the world of web design.… If you have not been baptized by fire in using something
as involved as Dreamweaver, then this book will be a great way to learn good web design. ”
— Robert Pritchett, MacCompanion
“Is it possible to learn real web design from a book format? Head First Web Design is the key to designing
user‑friendly sites, from customer requirements to hand‑drawn storyboards to online sites that work
well. What sets this apart from other ‘how to build a website’ books is that it uses the latest research
in cognitive science and learning to provide a visual learning experience rich in images and designed
for how the brain works and learns best. The result is a powerful tribute to web design basics that any
general‑interest computer library will find an important key to success.”
— Diane C. Donovan, California Bookwatch: The Computer Shelf
“I definitely recommend Head First Web Design to all of my fellow programmers who want to get a grip on
the more artistic side of the business. ”
— Claron Twitchell, UJUG
www.it-ebooks.info
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 the authors assume no
responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.
Lyza
Jason
Lyza Danger Gardner (@lyzadanger) is a dev. She In 2000, Jason Grigsby got his first mobile phone.
has built, broken, and hacked web things since 1996. He became obsessed with how the world could be
Curiously, Lyza was actually born and raised in a better place if everyone had access to the world’s
Portland, Oregon, the town where everyone wants to information in their pockets. When his wife, Dana,
be but no one seems to be from. met him, he had covered the walls of his apartment
with crazy mobile dreams. To this day, he remains
Lyza started college early and cobbled together a
baffled that she married him.
motley education: a BA in Arts and Letters from
Portland State University, followed by a master’s Those mobile dreams hit the hard wall of reality—
program in computer science at the University of WAP was crap. So Jason went to work on the Web
Birmingham (UK). until 2007, when the iPhone made it clear the time
was right. He joined forces with the three smartest
Lyza has written a lot of web applications (server‑side
people he knew and started Cloud Four.
devs, represent!), defeated wily content management
systems, optimized mobile websites, pounded on Since cofounding Cloud Four, he has had the good
various APIs, and worried a lot about databases. fortune to work on many fantastic projects, including
Fascinated by the way mobile technology has changed the Obama iPhone App. He is founder and president
things, she now spends a lot of time thinking about the of Mobile Portland, a local nonprofit dedicated
future of the Web, mobile and otherwise. to promoting the mobile community in Portland,
Oregon.
Since cofounding Cloud Four, a Portland‑based mobile
web agency, in 2007, Lyza has voyaged further into the Jason is a sought‑after speaker and consultant on
deep, untrammeled reaches of Device Land, exploring mobile. If anything, he is more mobile obsessed now
the foibles and chaos of mobile browsers and the mobile than he was in 2000 (sorry, sweetheart!).
web. She has an odd set of anachronistic hobbies,
You can find him blogging at http://cloudfour.com;
and it has been said that she takes a fair number of
on his personal site, http://userfirstweb.com; and on
photographs. She owns a four‑letter .com domain. We’ll
Twitter as @grigs. Please say hello!
bet you can guess what it is and go visit her there.
viii
www.it-ebooks.info
table of contents
ix
www.it-ebooks.info
table of contents
1
Responsive Web Design
Hey there! Are you ready to jump into mobile
Mobile web development is a wildly exciting way of life. There’s glamour and
excitement, and plenty of Eureka! moments. But there is also mystery and confusion.
Mobile technology is evolving at bewildering speed, and there’s so much to know!
Hang tight. We’ll start our journey by showing you a way of making websites called
Responsive Web Design (RWD). You’ll be able to adapt websites to look great on a
whole lot of mobile devices by building on the web skills you already have.
x
www.it-ebooks.info
table of contents
responsible responsiveness
2
Mobile-first Responsive Web Design
That’s a beautiful mobile site. But beauty is only skin deep.
Under the covers, it’s a different thing entirely. It may look like a mobile site, but it’s
still a desktop site in mobile clothing. If we want this site to be greased lightning on
mobile, we need to start with mobile first. We’ll begin by dissecting the current site
to find the desktop bones hiding in its mobile closet. We’ll clean house and start
fresh with progressive enhancement, building from the basic content all the way
to a desktop view. When we’re done, you’ll have a page that is optimized regardless
of the screen size.
xi
www.it-ebooks.info
table of contents
3
Facing less-than-awesome circumstances
The vision of a single, responsive Web is a beautiful one
in which every site has one layout to rule them all, made lovingly with a mobile-first
approach. Mmm…tasty. But what happens when a stinky dose of reality sets in? Like
legacy systems, older devices, or customer budget constraints? What if, sometimes,
instead of mixing desktop and mobile support into one lovely soup, you need to keep
’em separated? In this chapter, we look at the nitty-gritty bits of detecting mobile users,
supporting those crufty older phones, and building a separate mobile site.
xii
www.it-ebooks.info
table of contents
4
What devices should we support?
There aren’t enough hours in the day to test on every device.
You have to draw the line somewhere on what you can support. But how do you
decide? What about people using devices you can’t test on—are they left out in the
cold? Or is it possible to build your web pages in a way that will reach people on devices
you’ve never heard of? In this chapter, we’re going to mix a magic concoction of project
requirements and audience usage to help us figure out what devices we support
and what to do about those we don’t.
Definition
of where
to draw
the line
xiii
www.it-ebooks.info
table of contents
5
Get with the group
Setting the bar for the devices we support doesn’t take care
of a few nagging issues. How do we find out enough stuff about our users’
mobile browsers to know if they measure up before we deliver content to them? How do
we avoid only building (lame) content for the lowest common denominator? And how do
we organize all of this stuff so that we don’t lose our minds? In this chapter, we’ll enter
the realm of device capabilities, learn to access them with a device database, and,
finally, discover how to group them into device classes so that we can keep our sanity.
xiv
www.it-ebooks.info
table of contents
6
The Tartanator
“We want an app! Just a year or two ago, that hallmark cry generally meant
one thing: native code development and deployment for each platform you wanted
to support. But native isn’t the only game in town. These days, web-based apps for
mobile browsers have some street cred—especially now that hip cat HTML5 and
his sidekicks, CSS3 and JavaScript, are in the house. Let’s dip our toes into the
mobile web app world by taking a mobile framework—code tools designed to help
you get your job done quickly—for a spin!
xv
www.it-ebooks.info
table of contents
7
Super mobile web apps
The mobile web feels like that gifted kid in the class.
You know, kind of fascinating, capable of amazing things, but also a
mysterious, unpredictable troublemaker. We’ve tried to keep its hyperactive
genius in check by being mindful of constraints and establishing boundaries,
but now it’s time to capitalize on some of the mobile web’s natural talents.
We can use progressive enhancement to spruce up the interface in more
precocious browsers and transform erratic connectivity from a burden to a
feature by crafting a thoughtful offline mode. And we can get at the essence
of mobility by using geolocation. Let’s go make this a super mobile web app!
xvi
www.it-ebooks.info
table of contents
8
Tartan Hunt: Going native
Sometimes you’ve got to go native. It might be because you need
access to something not available in mobile browsers (yet). Or maybe your client simply
must have an app in the App Store. We look forward to that shiny future when we have
access to everything we want in the browser, and mobile web apps share that sparkly
allure native apps enjoy. Until then, we have the option of hybrid development—we
continue writing our code using web standards, and use a library to bridge the gaps
between our code and the device’s native capabilities. Cross-platform native apps
built from web technologies? Not such a bad compromise, eh?
xvii
www.it-ebooks.info
table of contents
9
Make (some) sense of the chaos
Responsive Web Design. Device detection. Mobile web
apps. PhoneGap. Waitwhich one should we use
There are an overwhelming number of ways to develop for the mobile web.
Often, projects will involve multiple techniques used in combination. There
is no single right answer. But don’t worry. The key is to learn to go with the flow.
Embrace the uncertainty. Adopt a future-friendly mindset and ride the wave,
confident that you’re flexible and ready to adapt to whatever the future holds.
xviii
www.it-ebooks.info
table of contents
leftovers
i
The top six things (we didn’t cover)
Ever feel like something’s missing We know what
you mean Just when you thought you were done, there’s more.
We couldn’t leave you without a few extra details, things we just couldn’t
fit into the rest of the book. At least, not if you want to be able to carry
this book around without a metallic case and caster wheels on the
bottom. So take a peek and see what you (still) might be missing out on.
ii
Gotta start somewhere
You can’t spell “mobile web without the “web. There are no two
ways about it. You’re going to need a web server if you want to develop for the mobile
web. That goes for more than just completing the exercises in this book. You need
somewhere to put your web-hosted stuff, whether you use a third-party commercial
web hosting service, an enterprise-class data center, or your own computer. In this
appendix, we’ll walk you through the steps of setting up a local web server on your
computer and getting PHP going using free and open source software.
xix
www.it-ebooks.info
table of contents
install WURFL
iii
Sniffing out devices
The first step to solving device detection mysteries
is a bit of legwork. Any decent gumshoe knows we’ve got to
gather our clues and interrogate our witnesses. First, we need to seek
out the brains of the operation: the WURFL PHP API. Then we’ll go track
down the brawn: capability information for thousands of devices in a single
XML data file. But it’ll take a bit of coaxing to get the two to spill the whole
story, so we’ll tweak a bit of configuration and take some careful notes.
iv
Take care of the environment
To be the master of testing native Android apps, you need
to be environmentally aware. You’ll need to turn your computer into a nice
little ecosystem where you can herd Android apps to and from virtual (emulated) or
real devices. To make you the shepherd of your Android sheep, we’ll show you how to
download the Android software development kit (SDK), how to install some platform
tools, how to create some virtual devices, and how to install and uninstall apps.
Index 417
xx
www.it-ebooks.info
the intro
:
er the burning question
In this section, we antswthat in a Mobile Web book?”
“So why DID they pu
1
It definitely helps if you’ve alre
Do you have previous web design and development
got some scripting chops, too. We’ady
not talking rocket science, but youre
experience?
Do you want to learn, understand, remember, and shouldn’t feel visceral panic if you
2 apply important mobile web concepts so that you can see a JavaScript snippet.
make your mobile web pages more interactive and
exciting?
2
Are you already developing mobile web apps or sites
and looking for a reference book on mobile web?
xxii intro
www.it-ebooks.info
the intro
t” read er as a learner.
We think of a “Head Firs
and then make sure
me thi ng First, you have to get it,
So what does it tak
e to lea rn so sed on the latest
t pu sh ing fac ts into your head. Ba
you don’t forget it.
It’s not ab ou hology, learning
, ne urob iol og y, an d educational psyc
e science
research in cognitiv ns your brain on.
n tex t on a pa ge . We know what tur
takes a lot more tha
ciples:
First lear ning prin
Some of the Head
Make it visual. Im
than morable
ages are far more me
mo re effective (up
learning much
words alone, and make
in recall
to 89% improvement
It web!
Watch out, mobile
and transfer studie s).
s mo re !
also makes thing Here we co me
understandable.
thin
Put the words wi
ap hic s they
or near the gr as
lea rne rs will be up to twice
on the bottom or on another page, and
relate to, rather than t.
ble ms related to the conten
likely to solve pro
rsonalized style.
nts
pe
In recent studies, stude
sa tio na l an d
Use a conver g tests if the content
spoke direct ly to
better on post-learnin ing a formal tone.
performed up to 40% tha n tak
firs t-p ers on , con versational style rather sly.
the reader, using a take yourself too seriou
d of lec tur ing . Use casual language. Don’t , or a lec ture?
Tell stories instea -party companion
pay mo re att ent ion to: a stimulating dinner
Which would you
re deeply. In other
ively flex your
mo
words, unless you act
er to th ink
Get the learn to be motivated, eng
aged, curious,
ch hap pe ns in your head. A reader has d for that,
neurons, nothing mu ate new knowledg An e.
ve pro ble ms , dra w conclusions, and gener tha t involve
and inspired to sol estions, and activit ies
ge s, exe rcis es, and thought-provok ing qu
you need challen
and multiple senses.
both sides of the brain
ion. We’ve all had the
he reader’s attent
Get—and keep—t ake past page one”
this, but I can’t stay aw
“I really want to learn s that are out of the ord
inary,
pays attention to thing
experience. Your brain a new , tou gh , technical
e, eye -ca tch ing , unexpected. Learning t.
interesting, str ang more quick ly if it’s no
e to be bo rin g. You r brain will learn much
topic doesn’t hav
xxiv intro
www.it-ebooks.info
the intro
We used redundancy, saying the same thing in different ways and with different media Structured content (HTML)
types, and multiple senses, to increase the chance that the content gets coded into more than
one area of your brain.
We used concepts and pictures in unexpected ways because your brain is tuned for
novelty, and we used pictures and ideas with at least some emotional content, because your
brain is tuned to pay attention to the biochemistry of emotions. That which causes you to
feel something is more likely to be remembered, even if that feeling is nothing more than a
little humor, surprise, or interest.
We used a personalized, conversational style, because your brain is tuned to pay more
attention when it believes you’re in a conversation than if it thinks you’re passively listening
to a presentation. Your brain does this even when you’re reading.
We included loads of activities, because your brain is tuned to learn and remember
more when you do things than when you read about things. And we made the exercises
challenging‑yet‑doable, because that’s what most people prefer.
We used multiple learning styles, because you might prefer step‑by‑step procedures,
while someone else wants to understand the big picture first, and someone else just wants
to see an example. But regardless of your own learning preference, everyone benefits from
seeing the same content represented in multiple ways.
We include content for both sides of your brain, because the more of your brain
you engage, the more likely you are to learn and remember, and the longer you can stay
focused. Since working one side of the brain often means giving the other side a chance to
rest, you can be more productive at learning for a longer period of time.
And we included stories and exercises that present more than one point of view,
because your brain is tuned to learn more deeply when it’s forced to make evaluations and
judgments.
We included challenges, with exercises, and by asking questions that don’t always have
a straight answer, because your brain is tuned to learn and remember when it has to work
at something. Think about it—you can’t get your body in shape just by watching people at
the gym. But we did our best to make sure that when you’re working hard, it’s on the right
things. That you’re not spending one extra dendrite processing a hard‑to‑understand
example, or parsing difficult, jargon‑laden, or overly terse text.
We used people. In stories, examples, pictures, etc., because, well, you’re a person. And
your brain pays more attention to people than it does to things.
xxvi intro
www.it-ebooks.info
the intro
1 Slow down. The more you understand, 6 Talk about it. Out loud.
the less you have to memorize. Speaking activates a different part of the brain.
Don’t just read. Stop and think. When the If you’re trying to understand something, or
book asks you a question, don’t just skip to the increase your chance of remembering it later, say
answer. Imagine that someone really is asking it out loud. Better still, try to explain it out loud
the question. The more deeply you force your to someone else. You’ll learn more quickly, and
brain to think, the better chance you have of you might uncover ideas you hadn’t known were
learning and remembering. there when you were reading about it.
4
is still better than feeling nothing at all.
Make this the last thing you read before
bed. Or at least the last challenging thing.
Part of the learning (especially the transfer to 9 Create something!
long‑term memory) happens after you put the Apply this to your daily work; use what you are
book down. Your brain needs time on its own, to learning to make decisions on your projects. Just
do more processing. If you put in something new do something to get some experience beyond the
during that processing time, some of what you exercises and activities in this book. All you need
just learned will be lost. is a pencil and a problem to solve…a problem that
5
might benefit from using the tools and techniques
Drink water. Lots of it. you’re studying for the exam.
Your brain works best in a nice bath of fluid.
Dehydration (which can happen before you ever
feel thirsty) decreases cognitive function.
Read me
This is a learning experience, not a reference book. We deliberately stripped out everything
that might get in the way of learning whatever it is we’re working on at that point in the
book. And the first time through, you need to begin at the beginning, because the book
makes assumptions about what you’ve already seen and learned.
We expect you to know HTML and CSS.
If you don’t know HTML and CSS, pick up a copy of Head First HTML with CSS &
XHTML before starting this book. We’ll explain some of the more obscure CSS selectors or
HTML elements, but don’t expect to learn about that foundational stuff here.
We expect you to feel comfy around web scripting code.
We’re not asking you to be a world‑class JavaScript expert or to have done a graduate
computer science project using PHP, but you’ll see examples using both languages
throughout the book. If the merest notion of a for loop makes you hyperventilate (or if
you have no idea what we’re talking about), you might consider tracking down a copy of
Head First PHP & MySQL or Head First JavaScript and then heading on back here.
We expect you to know how to track things down.
We’ll be blunt. The mobile web is an enormous topic, and mastering it involves expanding
your existing web development skills. There are too many things to know about the Web for
any one person to memorize, whether it’s a detail of JavaScript syntax or the specifics of a
browser’s support for an HTML5 element attribute. Don’t be too hard on yourself. Part of
the toolset of a good web dev is keeping your Google chops sharp and knowing when and
how to hit the Web to look up info about web topics. We bet you’re good at that already.
We expect you to go beyond this book.
It’s a big and beautiful mobile web world out there. We hope we can give you a shove to
start you on your journey, but it’s up to you to keep up your steam. Seek out the active
mobile web community online, read blogs, join mailing lists that are up your alley, and
attend related technical events in your area.
The activities are NOT optional.
The exercises and activities are not add‑ons; they’re part of the core content of the
book. Some of them are to help with memory, some are for understanding, and some
will help you apply what you’ve learned. Don’t skip the exercises. They’re good for
giving your brain a chance to think about the ideas and terms you’ve been learning in a
different context.
The redundancy is intentional and important.
One distinct difference in a Head First book is that we want you to really get it. And we
want you to finish the book remembering what you’ve learned. Most reference books don’t
have retention and recall as a goal, but this book is about learning, so you’ll see some of the
same concepts come up more than once.
xxviii intro
www.it-ebooks.info
the intro
Software requirements
As for developing any website, you need a text editor, a browser, a web server (it can be
locally hosted on your personal computer), and the source code for the chapter examples.
The text editors we recommend for Windows are PSPad, TextPad, or EditPlus (but
you can use Notepad if you have to). The text editors we recommend for Mac are
TextWrangler (or its big brother, BBEdit) or TextMate. We also like Coda, a more
web‑focused tool.
If you’re on a Linux system, you’ve got plenty of text editors built in, and we trust you
don’t need us to tell you about them.
If you are going to do web development, you need a web server. You’ll need to go to
Appendix ii, which details installing a web server with PHP. We recommend doing that
now. No, seriously, head there now, follow the instructions, and come back to this page
when you’re done.
For Chapter 5, you’ll need to install the WURFL (Wireless Universal Resource FiLe) API
and data. And for Chapter 8, you’ll need the Android SDK and some related tools. You
guessed it: there are appendixes for those tasks, too.
You’ll also need a browser—no, strike that—as many browsers as
possible for testing. And the more mobile devices with browsers you
have on hand, the better (don’t panic; there are many emulators you can use
if you don’t have hardware). The code and
For developing and testing on the desktop, we highly recommend Google’s resources for the
Chrome browser, which has versions for Mac, Windows, and Linux.
Learning how to use the JavaScript console in Google’s Chrome Dev Tools examples in the
is well worth the time. This is homework you need to do on your own. chapters are all
Last of all, you’ll need to get the code and resources for the examples in the
chapters. It’s all available at http://hf-mw.com.
available at
http://hf-mw.com.
The hf-mw.com site has the starting
point of code for all the chapters.
Head on over there and get downloading.
Bryan Rieger
Trevor Farlow
Andrea Trasatti
Ethan Marcotte
Stephanie Rieger
Trevor Farlow is an amateur baker, recreational soccer player, Bryan Rieger is a designer and reluctant developer with a
and part‑time animal shelter volunteer. When he’s not walking background in theatre design and classical animation. Bryan has
dogs, scoring goals, or perfecting his New York–style cheesecake, worked across various media including print, broadcast, web,
he can be found learning the art of product ownership in a lean, and mobile; and with clients such as Apple, Microsoft, Nokia,
mean, agile development team at Clearwater Analytics, LLC. and the Symbian Foundation. A passionate storyteller and
incessant tinkerer, Bryan can be found crafting a diverse range
Brad Frost is a mobile web strategist and frontend developer
of experiences at Yiibu—a wee design consultancy based in
at R/GA in New York City, where he works with large brands
Edinburgh, Scotland.
on mobile‑related projects. He runs a resource site called Mobile
Web Best Practices (http://mobilewebbestpractices.com) aimed at Stephanie Rieger is a designer, writer, and closet
helping people create great mobile web experiences. anthropologist with a passion for the many ways people interact
with technology. Stephanie has been designing for mobile since
Stephen Hay has been building websites for more than 16
2004 and now focuses primarily on web strategy, frontend
years. Aside from his client work, which focuses increasingly on
design, and optimization for multiple screens and capabilities. A
multiplatform design and development, he speaks at industry
compulsive tester and researcher, Stephanie is always keen to
events and has written for publications such as A List Apart and
discover and share insights on mobile usage, user behavior, and
.net Magazine. He also co‑organizes Mobilism, a highly respected
mobility trends from around the world.
mobile web design and development conference.
Andrea Trasatti started creating WAP content in 1999 on the
Ethan Marcotte is an independent designer/developer who
Nokia 7110, which in Europe was considered groundbreaking at
is passionate about beautiful design, elegant code, and the
the time. Andrea has led both WURFL and DeviceAtlas from
intersection of the two. Over the years, his clientele has included
their earliest days to success, and during those years built vast
New York Magazine, the Sundance Film Festival, the Boston Globe,
experience in device detection and content adaptation. You can
and the W3C. Ethan coined the term Responsive Web Design to
find Andrea on Twitter as @AndreaTrasatti, regularly talking
describe a new way of designing for the ever‑changing Web and,
about mobile web and new trends in creating and managing
if given the chance, will natter on excitedly about it—he even
content for mobile.
went so far as to write a book on the topic.
xxx intro
www.it-ebooks.info
the intro
Acknowledgments
Our editor:
Thanks (and congratulations!) to Courtney Nash, who pushed us to create
the best book we possibly could. She endured a huge raft of emails, questions,
ramblings, and occasional crankiness. She stuck with us throughout this book
and trusted us to trust our guts. And thanks to Brian Sawyer for stepping
up at the end and taking us over the finish line.
xxxii intro
www.it-ebooks.info
2 Chapter 1
www.it-ebooks.info
getting started
So you’re in the right spot at the right time. Mobile web is taking off,
and you’re ready to ride the rocketship. Let’s get started!
http://www.splendidwalrus.com
4 Chapter 1
www.it-ebooks.info
getting started
6 Chapter 1
www.it-ebooks.info
getting started
Here’s how Mike’s iPhone 4 renders the Splendid Walrus website. It doesn’t look so
great. Can you spot the problem areas? Mark any problems you see.
1 2
3 4
1 1
The navigation links
are all tiny and too
small to read or click.
3 The three-column
layout feels tight on
3
this screen resolution,
and the text is hard
to read.
2
2 The embedded 4
YouTube video
4 There is a weird gap
doesn’t work.
on the right edge
of the screen.
8 Chapter 1
www.it-ebooks.info
getting started
2 Fluid-grid layouts
Using relative CSS proportions instead of absolute
sizes for page layout elements. RWD uses percentages instead
of pixels as units for columns
and other layout elements.
3 Fluid images and media
Making our images and media scale to fit within
the size constraints of their containers by using
some CSS tricks.
10 Chapter 1
www.it-ebooks.info
getting started
styles.css
A multicolumn, big
CSS media queries layout when there’s
determine which of plenty of room
the CSS to apply to
which environments.
Somewhat
simpler layout
as the window
width decreases
“screen” is a media type. The rules between the Curious? If you’re the kind of
braces will only apply when person who reads technical specs for
the content is rendered on fun or to satisfy curiosity, you can
a screen. see all of the media types defined
in CSS2 on the W3C’s site at
Another way to use media types to apply CSS selectively is from www.w3.org/TR/CSS2/media.html.
within a <link> in your HTML document.
aspect-ratio
Media types, meet media features
height
You have certain features—your age, your height—and so do media
types. And just like The Splendid Walrus might want to establish a rule screen
that requires the minimum age of patrons to be 21 before they apply width
orientation
alcohol, we might want to define certain CSS that we only apply to
browser window widths within a certain range. “screen” is a useful
We’re in luck! width, along with color and orientation, is one media type.
of the media features defined in CSS3 for all common media types.
So, again, media types have media features. A few of the “screen”
media type’s media features.
Media features on their own don’t get us very far. We need a way to ask
the browser about the states of the ones we care about and, well, do
something about it. That’s where CSS3 media queries come in. P.S. There are more. But these
are the most useful to us.
12 Chapter 1
www.it-ebooks.info
getting started
Translating CSS media queries: You try it! Match the media query and its meaning.
14 Chapter 1
www.it-ebooks.info
getting started
<div class="navigation">...</div>
The three main <div class="header">...</div>
content columns <h1>...</h1> Putting the righthand
<div id="visit" class="column">...</div> column before the center
<div id="points" class="column">...</div>
column in the markup is
an old trick of the web
<div id="main" class="column">...</div> design trade: it makes it
<div class="footer">...</div> easier to handle layouts
using CSS floats.
The current, desktop‑oriented CSS lays out the page like this:
div.navigation
div.header
<h1>
div#visit
div#points
div.footer
div#main
Let’s go look at the CSS that
defines the layout and figure out
what needs to change to adapt it
to be mobile-sized.
16 Chapter 1
www.it-ebooks.info
getting started
<h1>
div#points
div#visit A single-column layout
sized for a 320-pixel
…to this browser width
div.footer
div.navigation
div#main
960 pixels
div.header
<h1>
div#visit
div#points
div#main
div.footer
320 pixels
/* Structure */
We need to change the width, body, .header, .navigation, .footer {
of the page and the header nts. width: 960px;
navigation, and footer eleme }
We don’t need this rule in .header, .navigation, .footer {
our mobile version (but it clear: both;
doesn’t hurt anything). }
The “columns” on the mobile , not
layout will lay out verticallye space
.column {
ated
Because nothing is flocle s
margin: 10px 10px 0 0;
horizontally. Let’s add som but
in our mobile layout, ar } between columns (vertically)
aren’t necessary. .navigation { get rid of the gutter.
min-height: 25px;
This is actually fine: we
want the navigation links }
to be at least this tall. .navigation ul li {
width: 320px; /* 960/3 */ We’ll use the same background
We need to adapt the } image for the header, so this
navigation link widths to can stay the same.
.header {
fit the smaller screen. background:url(images/w.png) no-repeat;
height: 200px;
} It might seem like we would need
#visit { to adjust the 200px height here,
width: 240px; but we don’t because we’ll use the
float: left; same image.
We need to remove the
floats and change the }
width of the visit and #points {
points columns. width: 240px;
float: right; We don’t need the margins for
} positioning anymore (#main
#main { will span the full width), and
margin: 10px 260px 0 250px;
we need to change the width.
width: 460px;
}
styles.css
18 Chapter 1
www.it-ebooks.info
getting started
3 Factor out the common CSS rules. We’ll do this in just a minute.
}
.column {
margin: 10px 0;
width: 320p width: 106.6667px;
x;
width:320px;
width: 106.6667px;
}
#visit, #points, #main {
width:320px;
}
20 Chapter 1
www.it-ebooks.info
getting started
Put it together
Here’s how we’ll put together the updated version of styles.css.
We didn’t make
Color, typography, and basic layout any changes to this
part of the CSS.
chapter1
}
@media screen and (max-width:480px) { point.png
} sample.jpg
styles.css
w.png
One last thing…
You’re going to need a viewport <meta> tag in the index.html file. These tags help
tell the browser how “zoomed in” to render the content. We’ll be taking a look at these
guys a bit later on, but for now, just take our word for it: you’ll want one of these.
index.html
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>The Splendid Walrus: Public House and Spirits</title>
styles.css
index.html
22 Chapter 1
www.it-ebooks.info
getting started
Test Drive
Once you’ve made these changes, load the index.html file in
your desktop browser and resize the window to less than 481
pixels wide to see the mobile‑friendly layout.
Watch out, mobile web!
Here we come!
Frank: This is really frustrating. I thought the mobile CSS we created would fix this.
Jill: Your CSS makes the layout fit on a smaller screen, but it’s still pretty rigid. I
mean, look what happens if I put my iPhone in landscape orientation.
Frank: Ugh. The layout is still 320 pixels wide…but on a 480‑pixel screen. Am I
going to have to write different CSS for every single different possible viewport size?!
Jill: See, this is where Responsive Web Design practices could help us. Right
now, you’re delivering a rigidly sized structure to all browsers whose current
window is 480 pixels wide or smaller, no matter what the actual specific browser
window width is. That’s not very flexible. I mean, not all mobile devices have a
320‑pixel‑wide browser window.
Responsive design helps us adapt our layout to different situations. Instead of
dictating the exact size of elements—that is, using pixel‑based measurements in our
structural CSS like we are now—we can use a proportional layout, which adapts
much better for different users.
Frank Jill
Frank: Proportional? Is that like ems and percentages and stuff in CSS?
Jill: Yeah, sort of. We can use percentages instead of pixels when we code up our
layout. That way, content stretches and shrinks to fill available space—kind of like
water filling in gaps. That’s why this kind of layout is often called a fluid layout.
And, by the way, this will help us fix that wayward image as well.
This photo is wider than
320 pixels, breaking out Frank: So, all of that work with media queries was wasted time.
of the layout. Jill: Not at all! Media queries are a big part of what makes responsive design work.
24 Chapter 1
www.it-ebooks.info
getting started
26 Chapter 1
www.it-ebooks.info
getting started
A fluid version
Left and right columns are of the layout
proportional: 25% of the at 1,200 pixels
window’s width.
Go fluid
There are a number of things we’ll need to do to address the problems
Jill found and move toward a responsive design.
Make the default body font size 100% so our page’s fonts
can scale up and down proportionally. If we’re going to make our
layout fluid, we’ll want
Fix the broken YouTube video. to be sure our fonts are
flexible, too.
Fix the image that is too wide.
A closer look
Let’s take a look at what this means, using the Splendid Walrus 960 pixels
site’s desktop layout.
We start with a context on which to base our proportions. In
this case, our reference design is 960 pixels wide. We want
our resulting, fluid layout to have the same proportions as the
current design does. So we’ll base our calculations on that 240 460 240
960‑pixel baseline. pixels pixels pixels
The navigation, header, and footer all span the full width of the
page. That makes the fluid formula very easy to apply indeed!
960 pixels
100%
960 pixels 960 pixels
28 Chapter 1
www.it-ebooks.info
getting started
The main, center column is a bit different. It doesn’t float. Instead, margins
are used to position the element. But that’s just fine. We can still use the
fluid formula to convert the pixel‑based margin sizes to percentages:
250 pixels
26.0416667%
Our current 960 pixels
CSS rule
#main {
Q: Why are there so many decimal places in
these numbers? Do we really need all that?
margin: 10px 260px 0 250px;
}
A: We’re demonstrating the purist fluid‑grid
approach here, which builds CSS units exactly as the
260 pixels numbers come off the calculator.
27.0833333%
Realistically, browsers round these very long numbers.
960 pixels
And—a bit concerningly—they round them in slightly
different ways.
Our updated CSS rule So, it’s up to you. You might consider rounding the
numbers down to one or two digits past the decimal
point. Another approach is to leave some play in
your layout—a percentage or two not accounted for
at all. Your grid won’t be as precise, but you avoid
some of the pitfalls of rounding issues and make your
#main {
Q:
}
Wait. Why is the top margin on .main still
10px? Isn’t that…wrong?
Not so fast!
Sometimes the “context” can change…
30 Chapter 1
www.it-ebooks.info
getting started
Context switching
Hey. I’m going to start offering
some new beer specials, and I want to
be able to feature those on the site—
can you adjust the design?
Mike’s pixel-based
CSS widths
960 pixels
220 pixels
22.916667%
960 pixels
960 pixels
The containing element of these images isn’t body (100% width,
or 960 pixels in our reference design), it’s div#main, which has a
width of about 460 pixels (47.91667% of 960 pixels in proportional
parlance). So we have just told the images to span a little less than 23%
of 460 pixels—too small!
960 pixels This is what you’ll get if you set the width of
img.label to be 22.916667%. Uh oh.
Do this!
960 pixels
220 pixels
47.826087%
240 460 pixels
240
pixels pixels
div.main New context: width
of div#main, the
containing element.
32 Chapter 1
www.it-ebooks.info
getting started
A sad farewell…
a get-out-of-jail-free
use the fluid technique on images and media, we have to
technique.
forego our old friends: the width and height attributes.
The CSS rule above will override a width attribute but will
not affect a height attribute. That means that, if we use Just because an image
height and width attributes, we could end up with an scales down on a
image that scales its width but not its height. End result: a narrower screen doesn’t mean that it
sad‑looking squished image in the wrong aspect ratio. isn’t still, at heart, a large image. An
800 KB JPEG is still an 800 KB JPEG,
OK, there are some workarounds for this, and removing even if it’s crammed down into a
these attributes is not awesome. But we’re going to jettison 120-pixel-wide column.
the height and width attributes for now.
In Chapter 2, we’ll talk about
techniques to deliver different images
to different devices and browsers,
saving on otherwise wasted bandwidth
and processor power (required to do
the actual scaling).
Still, it’s a powerful technique, and one
definitely worth having in your arsenal.
Make the default body font size 100% so our page’s fonts
can scale up and down proportionally.
34 Chapter 1
www.it-ebooks.info
getting started
Details, details
Let’s take care of a few remaining details to make our
Font Sizes Up Close
updated version of the Splendid Walrus site totally responsive.
With this edit to the CSS rule for the <body>
Set up flexible fonts element, we’re setting the baseline font size
So far, our layout is adaptive, but the fonts are stodgy for the page to be 100%. But what does 100%
and rigid. Just as percentages are the fluid ying to pixels’ mean? Here’s a quick‑and‑dirty (and approximate)
fixed‑width yang, ems are proportional font‑size units. Mike rule of thumb:
used ems in his original CSS, so we’ll just add the following 1em = 100% ≈ 12pt ≈ 16px
rule to the <body> element to be extra thorough:
But recall that we aim to adapt our content to
body { the user’s environment. If a user has changed
background: #f9f3e9; the browser’s font size, 100% is going to
represent a different absolute size.
color: #594846;
font: 100% "Adobe Caslon Pro", Also keep in mind that fonts on mobile devices
are a complex thing, and that in some cases,
"Georgia", "Times New Roman", serif;
1em might equate to a (significantly) different
} point or pixel size.
Remember to be responsible
Just like fluid image resizing doesn’t actually reduce the file size of
images, neither does fluid media change the size of the actual media.
It’s up to you to determine whether using video (or other multimedia) on
mobile devices is worth the file size and processor oomph required for
playback.
OK! Let’s get all of these changes in place to give The Splendid Walrus a mobile‑friendly site
that uses Responsive Web Design techniques.
2 Identify the structural CSS rules that are common between both mobile
and desktop variants now that they are proportional (page 34). Remove
these rules from the media‑query‑specific sections and put them in the
common structural section of the CSS file.
3 Add the CSS from page 33 to implement fluid images (and media).
4 Update the CSS rules for the <body> element to add a proportional
font size baseline (page 35).
36 Chapter 1
www.it-ebooks.info
getting started
Q: OK. I’ve seen ems as units in CSS, Q: Is there any other use for CSS Q: If CSS3 isn’t all the way “done,” do
but I don’t quite get it. What’s the point? media queries beyond the mobile web? browsers support it?
A: 1em is—unspectacularly—a
representation of the current font size, in the
A: Definitely. An example: just as mobile
devices often represent the lower end of
A: Like we said, it’s a jungle out there.
Adoption for some of the more complete
current context. That doesn’t sound terribly the screen resolution spectrum, some of the pieces of CSS3 is becoming widespread, but,
exciting. But the magic comes when you newer widescreen monitors and televisions as we’ll see a bit later, is far from something
define your font sizes in relation to this. So, have very high resolution. Sometimes it that can be assumed in the mobile space.
if you set your <h1> element to display at makes sense to adapt a layout—say, to add
1.5em, it will be 150% of the baseline font
size of its containing element.
more columns—for these window widths. Q: Why does the right column show
up before the main column in the mobile
You can actually use the same fluid formula
Q: What actually caused the weird layout?
to generate fluid, em‑based font sizes from gap at the right side of the screen in the
fixed font sizes. To create a fluid version
of an 18‑point font in a context where the
exercise way back on page 7? A: The div#points content comes
before the div#main content in the
baseline font is 16 points, you can do A: This one’s iPhone‑specific. When
displaying a web page “zoomed out” (i.e.,
HTML markup. In the desktop layout, floats
18/16 = 1.125em (target/context = are used to position the #points content,
result). when it’s acting like a desktop browser), such that it appears to the right of the
mobile Safari on the iPhone assumes a #main content. The mobile layout doesn’t
Q: Wait. Why is it 1.125em instead of
viewport width of 980 pixels. Before mobile
optimization, the Splendid Walrus layout was
use floats, and as such, the content is
displayed in the order it occurs in the HTML.
112.5%?
960 pixels wide, which leaves an awkward,
Let’s walk through the resulting CSS file and look at our changes.
body {
background: #f9f3e9;
color: #594846;
font: 100% "Adobe Caslon Pro", Georgia,
This is right near the "Times New Roman", serif;
top of the CSS file. }
.header, .footer {
clear: both;
}
.header {
background:url(images/w.png)
no-repeat;
Shared structural CSS height: 200px;
}
.navigation {
min-height: 25px;
}
img, object {
max-width: 100%;
}
.navigation ul li {
width: 33.333%;
}
.header, .footer, .navigation {
width: 100%;
}
38 Chapter 1
www.it-ebooks.info
getting started
D O
TO va rious w
indow siz
es
at
shots
Screen
40 Chapter 1
www.it-ebooks.info
getting started
Fluid-grid layouts
+
CSS media queries
Responsive
+ = Web Design!
Fluid images/media
The mobile web is not unlike the Wild West—it’s full Media types (e.g., screen, print, projection)
of surprises and adventure. The mobile web browser have media features (width, color,
landscape is diverse, and, sometimes, crazy‑making. monochrome, orientation). It’s these media
Just because we can use the same layout on a mobile features we evaluate in our media queries.
device as in a “traditional” browser doesn’t mean we A CSS media query is a logical expression. When it
necessarily should. evaluates to TRUE, the enclosed CSS rules are applied.
Responsive Web Design (RWD) is a collection of A fluid layout is one that uses proportional widths instead
approaches to make our web content adapt to the user, of fixed widths such that the content of the page scales
not the other way around (forcing the user to look at and flows naturally across a range of window widths.
rigidly formatted pages).
Fluid images are a CSS technique that keeps outsized
RWD is a combination of CSS3 media queries, fluid- images (or media) from “breaking out” of their parent
grid layouts, and fluid images. It’s also a way of elements when the parent element width is smaller than
thinking about layout and content. that of the image (or media). The images and media
CSS3 media queries let us apply CSS selectively to scale down as the parent element scales down.
different user environments based on the current value Using a simple font-size reset on the <body>
of relevant media features. element and defining font sizes in ems or percentages
keeps our type fluid.
2 responsible responsiveness
Mobile-first
Responsive Web Design
Darling, I don’t care if you are cold.
If you knew how much optimization it
had taken to look this good, you’d wear
a bikini on the beach in winter, too.
w.com/ch2/chapter2/ontap.html.
Check out the On Tap Now page at http://hf-m
44 Chapter 2
www.it-ebooks.info
responsible responsiveness
Proxy server
Mobile phone The Internet
Web server
You don’t need a fancy server.
Your personal computer can
act as a proxy server with
the right software.
46 Chapter 2
www.it-ebooks.info
responsible responsiveness
Test Drive
Ready for some detective work? It’s time to figure out why the On Tap Now page is slow.
48 Chapter 2
www.it-ebooks.info
responsible responsiveness
Top part of th
There’s gold in ’em HAR hills Mobitest resultes Bpalaze
ge.
There is a nugget buried in the Blaze Mobitest
results page behind the tiny View HAR file link.
Click that link, and you will go to a new site
called the HTTP Archive Viewer and see a more
detailed waterfall than the test results page.
This waterfall chart shows us every resource that
the browser downloaded in much more detail
than the picture of the waterfall on the Blaze
report page.
You’ll find the
sa
The preview tab contthaine page link next to the“VTw
iew HAR file”
fo r itter and
waterfall chart ted
Facebook links.
we tested. It was genera HTTP Archive (HAR) Viewer
from a HAR file.
be used
The HAR file cafanll charts.
to make water t HAR at
Read more abou
httparchive.org.
50 Chapter 2
www.it-ebooks.info
responsible responsiveness
Click the plus sign to get more details The HTTP response The bar graph shows when the file request
about what the browser asked the code from the server. started and when the file complet
server and how the server responded 200 means “OK.” downloaded. Only a few files can beely
(aka the HTTP headers). downloaded at the same time.
Review the waterfall chart for the On Tap Now page. Find the five largest files and examine
them. For each file, answer:
What does this information tell you about what you might need to do to make the page faster?
Did you find the problems with the page? Let’s review.
52 Chapter 2
www.it-ebooks.info
responsible responsiveness
taps.css
Mike hid the map with CSS
Mike figured out how we used media queries to @media screen and (max-width:480px) {
modify the layout for mobile. He added in his own
.
CSS rule inside our media query. The rule Mike e rules
added sets the display for the iframe to none. . There are many mor
. in the CSS fi le .
Unfortunately, while setting the display to none
will prevent the map from showing up, it doesn’t #map {display:none;}
prevent it from downloading. }
54 Chapter 2
www.it-ebooks.info
responsible responsiveness
► Basic HTML
s
of ad st for brow
► Small images
► Limited CSS and JS
e
S to t
t
Use J
r
Small screens
► Simple layout
s u
phone size
at es
Larger screens
► Larger images
(desktops and TVs)
► For TVs, optimize
navigation for use by
people sitting 10 feet
away who are using a
remote control
*These are just examples of enhancements. What you do depends on the project.
56 Chapter 2
www.it-ebooks.info
responsible responsiveness
Mobile first is like a small‑plate diet. Simply by eating on a For example, content surrounded by an
smaller plate, you’re likely to eat less food. <h1> tag is more important on the page
than content marked up with an <h2>
The desktop home page is an all‑you‑can‑eat buffet. All sorts of or a <p> tag.
junk gets thrown on it.
class and id attributes can also add
Mobile is a small plate. You have to choose carefully and semantic meaning to documents if their
prioritize your content. values are things like calendar and
And once you’ve got a focused mobile site, you’re better prepared not presentation values like left or
to ask the tough questions like whether or not the things that top. Many web developers use classes
didn’t make the cut for mobile are really important enough to in a standard way called microformats to
add back in for desktop. provide more semantic meaning. Learn
more at www.microformats.org.
Semantic markup doesn’t mean you
completely avoid tags like <div> and
<span> that don’t add meaning. Instead,
you choose the right semantic tags and
attributes for the content of a page
whenever possible.
Fix CSS background images so that only one file gets downloaded per
image. Make sure display:none is being used appropriately.
Use JavaScript to add Google Maps to the page when the browser can
support it and the document is wide enough to accommodate it.
<div class="navigation">...</div>
<div class="header">...</div>
<h1>...</h1>
Two columns <div id="visit" class="column">...</div> Instead of a <div> called
instead of “main,” Mike has created a new
<div id="ontap" class="column">...</div>
three column with the id of “ontap.”
<div class="footer">...</div> That <div> contains the list of
current beers.
Because we did a good job of creating a template with semantic markup,
the document is clean and simple already. It looks like our main task to
make the content mobile first will be removing the Google map.
Because we’re going to need to reference the code later, let’s use HTML
comments to prevent the iframe from being included in the page.
ame by
Comment out the Google Maps--ifr>. Find the iframe in the #visit <div>.
surrounding it with <!-- and
<!--
<iframe id="map" width="300" height="300" frameborder="0" scrolling="no"
marginheight="0" marginwidth="0" src="http://maps.google.com..."></iframe>
-->
58 Chapter 2
www.it-ebooks.info
responsible responsiveness
<div class="navigation">...</div>
<div class="header">...</div>
<h1>...</h1>
<div id="ontap" class="column">...</div>
<div id="visit" class="column">...</div>
<div class="footer">...</div>
60 Chapter 2
www.it-ebooks.info
responsible responsiveness
styles
content and build up to the desktop (and beyond).
Small scr
But first we have a confession. Mobile first is a little bit of a misnomer when it
comes to the CSS. Before we apply any media queries for small screens, we’re
ee
n styles
going to set all of the basic styles—for color, type, etc.—and then enhance them.
Large scr
There is a good reason for doing this. Many mobile browsers don’t understand
media queries at all. So we need to make sure they at least get the basic
ee
n styles
style rules.
Test Drive
We’ve made quite a few changes to the page: • Removed Google Maps • Fixed the floats
• Reordered the markup • Reordered the media queries
We better check to make sure things still work. Load the page in a few desktop and mobile browsers
to see how it looks. Be sure to check Internet Explorer.
and
owser is less than (lt) IEMo9 bile
This tests to see if the(!IbrEM obile). We exclude IE
that it isn’t IE Mobile e mobile layout. IE9 and above See the full syntax for conditional
because it should get th so they don’t need the extra help. comments at http://bit.ly/ie-comments.
understand media queries,
Look carefully. The <!--[if (lt IE 9)&(!IEMobile)]>
HTML comment <link rel="stylesheet" type="text/css" href="layout.css" media="all" />
opens on the first
line, but doesn’t <![endif]-->
close until “-->” is
included on the final
line. Other browsers If the conditions are met, IE will do whatever is in between the opening [if]
will see this as a statement and the closing [endif]. The example shows a link to a CSS file,
comment and ignore but it could be anything you would find in an HTML document.
its content.
62 Chapter 2
www.it-ebooks.info
responsible responsiveness
taps.css After you copy them, remove the rules and the
surrounding media query from taps.css. We’ll
reapply the rules to the HTML document next.
layout.css
/* Wider viewports/higher resolutions
(e.g. desktop) */
@media screen and (min-width:481px) {
.column { .column {
margin: 10px 1.04166667% 0 0; margin: 10px 1.04166667% 0 0;
} }
#visit { #visit {
margin: 0 68.75% 0 0; margin: 0 68.75% 0 0;
} }
#points { Copy these #points {
width: 25%; rules to width: 25%;
float: right;
your new float: right;
file.
} }
#main { #main {
margin: 10px 27.0833333% 0 margin: 10px 27.0833333% 0
26.0416667%; 26.0416667%;
} }
#ontap { #ontap {
width: 67%; width: 67%;
float: right; float: right;
margin: 10px 0 0 0; margin: 10px 0 0 0;
} }
}
Add this link tag The 481px value for min-width was
copied from the media query we This is the media query syntax
to ontap.html. for link tags that you learned
removed from taps.css.
in Chapter 1.
64 Chapter 2
www.it-ebooks.info
responsible responsiveness
Q: With super-fast 4G phones on the Q: You mentioned that setting up a Q: It seems like the order of content
horizon, is performance really that big of proxy server might make sense. What do may often be different between desktop
a deal? you recommend? and mobile. How do you handle this in
more complex pages?
A: Absolutely. Even 4G phones end up on
the EDGE network occasionally (EDGE is
A: There are many proxy servers,
including some fantastic open source ones. A: Ah, you caught that, huh? Yes, this
an older, slower network). Studies show that We happen to be fans of a commercial is one of the common challenges for
slow sites decrease usage and directly affect product called Charles Proxy. Responsive Web Design. In the long run,
the bottom line. the Flexible Box Module (Flexbox) in CSS3
Q: Q: The lack of plug-ins seems like a promises an easy way to reorder content in
stylesheets. Combine Flexbox with media
Why am I getting different results big deal. How do you get anything done
from the Blaze Mobitest? without Firebug and Web Inspector? queries, and you can completely reorder
pages as needed. Unfortunately, Flexbox
is still young and isn’t fully supported. So
A: There are many reasons why this
can occur. Page download time will change
A: It isn’t easy. First, a lot of your
debugging work can be done in a desktop
developers resort to JavaScript to reorder
content or combine RWD with device
with every test depending on network traffic. browser so long as you are careful to test on
detection (see Chapter 5). Frankly, content
Google Maps code is different for each real devices at some point in the process.
ordering and image handling remain two of
operating system and may change over time.
There are also a lot of new tools that attempt the biggest challenges for RWD.
The behavior of the phones will also change
to get around the plug‑in limitations. The
as new versions of the operating systems
are released. For the book, we tested using
Mobile Perf Bookmarklet (http://bit.ly/
mw-perf) includes many performance tools.
Q: Will the versions of IE that don’t
Blaze’s iOS 4.3, Android 2.2, and Android support media queries see the responsive
weinre (http://bit.ly/mweinre) and Opera design? Aren’t media queries necessary?
2.3 test devices.
Dragonfly (http://opera.com/dragonfly) let
Don’t worry too much about the variations
in test results. What matters is the code and
you run Web Inspector on your desktop
and examine what is going on in the phone
A: Internet Explorer will display the
desktop version. It will still have the fluid
images being downloaded unnecessarily. browser.
grids and flexible images. But it won’t
change based on any of the media query
Q: By separating the stylesheet into Q: It doesn’t seem like much changed instructions. If media query support is
two files, aren’t you making the site load when we switched to mobile-first media critical, there is an open source library
more slowly? queries. Why bother? called Respond.js that fills in support for
media queries for older IE versions. This is
A: It is true that the number of HTTP
requests makes a big difference in the
A: For this page, there wasn’t a big
difference between a desktop‑first CSS file
a fairly intensive script, so be sure to test
extensively if you decide to implement it.
download speed. So we shouldn’t recklessly and a mobile‑first one. In our experience,
add requests. In this case, we thought it however, this is the exception. With more
made more sense to separate them so IE complex styles, you often want the wider
could use the same file. rules to override some, but not all, of the
styles set for smaller screens. Reordering
the media queries ensures that the CSS
cascading behavior is consistent with the
goal of progressively enhancing the page as
the screen gets wider.
Make the HTML as simple as possible and swap the order of the CSS
so that the mobile version is first.
Fix CSS background images so that only one file gets downloaded per
image. Make sure display:none is being used appropriately.
Use JavaScript to add Google Maps to the page when the browser can
support it and the document is wide enough to accommodate it.
Test Drive
Check the On Tap Now page using the Blaze Mobitest to make sure taps.jpg is
no longer being downloaded. Try both iPhone and Android devices. You can
use http://hf-mw.com/ch2/ex/3/ontap.html if your copy of the page is not on a
public server.
66 Chapter 2
www.it-ebooks.info
responsible responsiveness
It works on iPhone,
but the image is still
downloading on Android.
We’d argue that imag It looks like we can make the taps.jpg image smaller with some basic web
optimization has e image optimization. Changing the JPEG quality from 80 to 45 makes the
always been paramount. image 78 KB instead of 440 KB,
Faster connections ar and you have to look very closely to
never a given, even fo e see any difference in image quality.
destkop computers. r zation,
For more on web image optimi ML
see Chapter 5 of Head Fir HT
st
with CSS & XHTML.
Images still not small enou
Smush them further at gh?
www.smushit.com.
labels on the On
There are 16 beerat use an <img> tag Despite the need for multiple versions of this image depending on
the
Tap Now page thr Benson’s Bubbler. screen size, HTML only allows one value for the src.
like this one fo
<img src="brews_images/bensons_bubbler.jpg" alt="Benson's Bubbler">
It’s tempting to replace the value of the src attribute using JavaScript.
Unfortunately, most browsers look ahead at the HTML document and preload
CSS can’t be used to
images before the JavaScript has been fully evaluated. This often means
override the value of the
one size file downloads before the JavaScript changes the src, resulting in
src attribute, either.
duplicate downloads and causing the browser to reflow the page layout.
full URL of
Set the first part of the src to Replace with your domain and After the slash, addtothehave resized.
http://src.sencha.io/. path to the images. the image you want
<img src="http://src.sencha.io/http://[DOMAIN]/[PATH]/brews_images/bensons_
bubbler.jpg" alt="Benson's Bubbler">
68 Chapter 2
www.it-ebooks.info
responsible responsiveness
Test Drive
We should have an efficient, fast, mobile‑optimized web page now. Test it
using www.blaze.io/mobile to see how we did. Select the option to have Blaze
run three tests on the phone to get an average. Compare the total file size
and download time of the new page to the original page.
If your pages are not publicly accessible, you can test using
http://hf-mw.com/ch2/ex/4/ontap.html.
Before
After
70 Chapter 2
www.it-ebooks.info
responsible responsiveness
Q: Why do browsers download CSS images that are Q: What about other media? Do video and audio suffer
never used? from the same problems?
ains a
The content attribute cont instructions
comma-separated list of of the Width of the viewport. Can be set
for the browser. See all/metaviewport. pixels or can be set to “device-widthin,”
What type of options at http :// bit .ly
which tells the browser to match
<meta> tag is this? viewport to the device resolution. the
Sets the initial scale (or zoom Declares a limit on The maximum-scale
level) of the page. Setting it to 1 how much the page is what is preventing
means that the document should be can be scaled up. the users from
displayed at its normal scale. There is also a similar zooming the page.
minimum-scale setting.
72 Chapter 2
www.it-ebooks.info
responsible responsiveness
Make the HTML as simple as possible and swap the order of the CSS
so that the mobile version is first.
Fix CSS background images so that only one file gets downloaded per
image. Make sure display:none is being used appropriately.
Use JavaScript to add Google Maps to the page when the browser can
support it and the document is wide enough to accommodate it.
snippet that
Remember this iframeWe’re going to use
we commented out?rt it into the page.
JavaScript to inse
<!--
<iframe id="map" width="300" height="300" frameborder="0" scrolling="no"
marginheight="0" marginwidth="0" src="http://maps.google.com..."></iframe>
-->
74 Chapter 2
www.it-ebooks.info
responsible responsiveness
Do this!
ript
go in g to ne ed a co ntainer for the JavaSc
We’re add a <div> here.
to reference, so we’ll
76 Chapter 2
www.it-ebooks.info
responsible responsiveness
<div class="footer">
<p>See you soon! Love, The Splendid Walrus</p>
We’re going to add our </div>
JavaScript as the very last [INSERT SCRIPT HERE]
thing on the page before the
closing </body> tag.
</body>
</html>
Time to put our work to the test. Grab ontap.html and answer the following:
78 Chapter 2
www.it-ebooks.info
responsible responsiveness
80 Chapter 2
www.it-ebooks.info
responsible responsiveness
<script type="text/JavaScript">
var breakpoint = 481,
id = 'mapcontainer',
viewportWidth = window.innerWidth;
if (viewportWidth > breakpoint) {
var mapElement = document.createElement('iframe');
mapElement.id = 'map';
mapElement.width = '300';
mapElement.height = '300';
Delete thesethe
mapElement.frameborder = '0';
Test Drive
Save layout.css and ontap.html. Load the On Tap Now page in Safari.
You can use http://hf-mw.com/ch2/ex/6/ontap.html if it’s more convenient. How
does the map look?
After adding
the two new lines,
your #map rule in #map {
layout.css should width:100%;
look like this.
height:400px;
border:none;
overflow:hidden;
margin:0;
min-width: 200px;
}
82 Chapter 2
www.it-ebooks.info
responsible responsiveness
The map is co
again when thevering up the beer labels
window is narrow
.
84 Chapter 2
www.it-ebooks.info
responsible responsiveness
click
Load the On Tap Now page in the browser with the Window Size bookmarklet
(or a browser extension). Activate the bookmarklet. Resize the browser.
Write down the width of the browser when the layout breaks or the
content looks odd.
86 Chapter 2
www.it-ebooks.info
responsible responsiveness
Lightweight and
fast on mobile
You can use
http://hf-mw.com/ch2/ex/
Our mobile-first responsive design is complete to run your own speed tests. 8/ontap.html
Make the HTML as simple as possible and swap the order of the CSS
so that the mobile version is first.
Fix CSS background images so that only one file gets downloaded per
image. Make sure display:none is being used appropriately.
Use JavaScript to add Google Maps to the page when the browser can
support it and the document is wide enough to accommodate it.
88 Chapter 2
www.it-ebooks.info
responsible responsiveness
Q: What exactly is a viewport? Q: What are breakpoints? Q: Why does the overlap with the map
occur in the first place?
A: Imagine taking a sheet of cardboard A: Breakpoints are just a fancy way of
and cutting out a rectangle in the middle of
it. Lay that rectangle over your monitor so
describing the resolution at which a designer
decides to change the layout of a page. This
A: Because the map is an element that
doesn’t scale with the browser window.
you can only see the portion of the web page is usually done via media queries checking When the window is small, the browser can’t
that shows through the rectangle. That’s to see if a page is narrower or wider than a scale the map any smaller, so the left column
what a viewport does for web pages. certain number of pixels. ends up overlapping the right column.
A complex responsive design may have
Q: So the viewport <meta> tag multiple breakpoints, including some that Q: Doesn’t adding a min-width
tells the browser what size to make the make wholesale changes to the layout as to the map break the responsive design
viewport? well as some minor breakpoints that only by creating an element that doesn’t scale
make a few targeted tweaks to fix minor with the browser window?
A: Exactly. By default, iOS sets the
viewport to 980 pixels. If you’ve optimized
layout issues.
A: Technically, yes. It seems like a decent
your page for smaller screens, setting
the <meta-viewport> tag lets the
Q: I don’t want to prevent people solution here because we’ve modified the
media queries to address overlapping
from zooming, but that iOS bug is pretty
browser know to set the viewport accordingly. heinous. Is there any way to enable content. Another option would have been to
zooming and not have a broken page? use media queries to adjust the dimensions
of the map and proportions of the columns.
A: You can find a JavaScript workaround
at https://gist.github.com/901295.
Adding media queries to an existing desktop site may Mobile‑first RWD is another form of progressive
make it look good on mobile, but doesn’t mean that it is enhancement that uses screen size to determine how
mobile optimized. to enhance web pages.
Because most mobile browsers don’t support plug-ins, Designing for mobile first forces you to focus on what
there are fewer tools to assist mobile web developers. really matters, thus helping you remove cruft from
Using a proxy server or a testing solution like Blaze pages.
Mobitest can help you see what is actually getting Internet Explorer 8 and below do not support media
downloaded by a mobile browser. queries. Conditional comments are a workaround.
HTTP archive files and waterfall charts are essential JavaScript can augment media queries by testing for
performance tools. screen size and adding content when appropriate.
Mobile-first Responsive Web Design helps optimize Instead of designing breakpoints based on the typical
web pages by making sure that smaller resources are screen resolutions, let the content dictate the
downloaded by default. resolutions at which you need to modify the layout.
Facing less-than-awesome
circumstances
Beautiful, harmonious,
responsively designed websites
that work for all browsers and
devices known to man...was it all
but a wonderful dream?
Creature Comforts’
VP of Communication
92 Chapter 3
www.it-ebooks.info
a separate mobile site
Frank: I’ve got a bit of bad news. Creature Comforts doesn’t have
a very big budget. There are some internal politics involved. And it
would take a huge effort to extract the group’s administrative and
content‑publishing processes from its older, proprietary CMS. We can’t
touch the desktop site, at least for now.
Jim: Doesn’t that make our job impossible?
Frank: No, but it might require a bit of compromise. Creature
Comforts’ website is big and complicated, but the only part the group
feels it is vital to make mobile‑optimized is its so‑called Comforts
Logistics Portal. This web application lets agents give and receive
updates and coordinate scheduling and supply drops. This part of the
desktop website is relatively contained and has APIs that we can use.
Jim: I don’t get it. How do we selectively change only part of the site?
Frank: In this case, I think we’re going to need to develop a separate
site for mobile users.
Jim: That sounds messy.
Frank: The mobile web can be a messy job. You know that. We need
Jim to make this work, and work reliably, for a lot of people scattered
Frank
around the globe. This is not the spanking‑new‑smartphone crowd,
either. A lot of the staff members’ devices are donated, older phones,
and the mobile connections in some of the areas they serve are spotty
Sometimes it makes
at best. We need a lean, simple, and functional mobile website that
helps these folks get their jobs done. We simply can’t wrangle their
sense to create a
existing desktop stuff into what we need.
separate, standalone
site for mobile devices. Scared of programming?
Don’t sweat it too much.
There is some talk of APIs and web
applications whirling around, but
we won’t make you do any of the heavy lifting. Leave
the programming up to us—your job is to help us
make it look good and work well on the mobile web.
94 Chapter 3
www.it-ebooks.info
a separate mobile site
CMSes let administrative users, who might not be familiar with HTML A: The number of CMSes out there is bewildering. Some are more
easily adapted for mobile devices than others. The problem of mixing
markup or web design, create and manage content.
content, logic, and presentation is certainly one suffered by many
There are CMSes in both the open source and commercial spaces, popular CMSes.
written in every programming language you can think of. Examples The development communities and companies behind many CMSes
include WordPress, Drupal, DotNetNuke, Joomla!, and SharePoint. are actively working on subsequent releases that are optimized for
Larger or specialized organizations sometimes create their own CMS delivering content to different types of clients. And forward‑thinking
software. folks in the mobile web world are reimagining ways of structuring
content—treating content more systematically, like application data,
Most CMSes also handle the publishing of content, using templating to makes its reuse across multiple platforms more straightforward.
systems or other mechanisms. This can make the transition to
support mobile devices tricky, as, in many cases, the content is
tangled up with presentation layers.
APIs Up Close
Different kinds of
devices and browsers
request the website (e.g.,
www.example.com).
m.example.com www.example.com
96 Chapter 3
www.it-ebooks.info
a separate mobile site
A user-agent string is a
piece of text that serves
as a sort of ID card for
a client application (in
our case, web browsers).
Each unique browser is
a unique user agent.
“User agent” is often
abbreviated to “UA.”
Host: www.example.com
Accept: text/html,application/xhtml+xml,application/xml
Accept-Encoding: gzip,deflate,sdch Request headers
Referer: http://www.example.com/foo
User-Agent: Opera/9.64(Windows NT 5.1; U; en) Presto/2.1.1
User-agent archaeology
The structure of user‑agent strings today is a curious and sometimes confounding
patchwork of convention, confusion, and trickery. Full order has never successfully
been imposed over how they are written. So you can end up with things like:
Why would the user agent for Chrome on Windows mention Safari? What’s
KHTML, and how is it “like” Gecko? Like your appendix or the stumpy leg
remnants in whales, some of this is evolutionary cruft.
The vestigial “Mozilla compatibility flag” (Mozilla/5.0 in the example above) is
practically omnipresent to this day, though it doesn’t mean much anymore. Mentions
of Mozilla, KHTML, Gecko, or WebKit are UAs’ way of claiming that their layout
engines are comparable to or “better” than those. At the time of this writing, all
WebKit‑based browsers on mobile devices except for Android mention “Safari” in
their user‑agent string (Apple originally developed WebKit, basing it on KHTML).
98 Chapter 3
www.it-ebooks.info
a separate mobile site
MSIE 7.0
Safari/535.1
This browser is
KHTML, like Gecko
“compatible with” Java runtime for
Mozilla/5.
0 or historically Profile/MIDP-2.1
mobile devices
Mozilla/4.0
based upon…
Configuration/CLDC-1.1
1
Mozilla/5.0 (Linux; U; Android 2.1; en-us; ADR6200 Build/ERD79)
AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17
2 Presto/2.1.1
Opera/9.64(Windows NT 5.1; U; en)
3
Mozilla/5.0 (BlackBerry;
U; BlackBerry 9800; en-US)
(KHTML, like Gecko) Versio AppleWebKit/534.1+
n/6.0.0.246 Mobile Safari
/534.1+
You’ve seen a few user‑agent strings dissected. Now you try it. Match each snippet,
extracted from the user‑agent strings above, to its purpose.
100 Chapter 3
www.it-ebooks.info
a separate mobile site
SOlUTion
102 Chapter 3
www.it-ebooks.info
a separate mobile site
A few reasons. Two common motivations you ask for. Disagreement abounds between
Q: What about the other parts of user-
are privacy and the desire for a specific
experience. Some users don’t want to share
developers on this point. There be dragons.
Tread lightly.
agent strings on page 99 that you didn’t
information about what browsers they are
explain? What does en-us mean? What
does U mean?
using. In other cases, a user might want
to try to see web content in a particular
Q: Hey, you totally neglected to
mention UAProf.
way. A popular example is the “desktop
A: The “en‑us” is language information,
and means that the browser and its interface
mode” available in several mobile browsers. A: Many mobile devices send UAProf
By turning this on, users are often (and (User‑Agent Profile) headers when making
elements are localized for English, US‑ sometimes unknowingly) causing the requests, often (but not always) as the
style. The “U” indicates that the browser browser to send a different User-Agent
has “strong” security (as opposed to “I” for
x-wap-profile request header. The
header, one that looks more like a desktop UAProf specification gives mobile handset
“weak” security, or “N” for no security at all). browser. Sometimes this is done sanely, manufacturers a way to provide information
To analyze other various bits of user‑agent and is just fine—Windows Phone 7 desktop about the device. Usually, a link to the
strings like this, make a trip to the ever‑so‑ mode user agents are relatively easy to spot. location of the UAProf is provided in the
useful www.useragentstring.com. But not always. Take a look at the user‑ request header.
agent string that one of the Android versions
Q: Is there seriously a different user of the mobile browser Skyfire sends when in This sounds pretty good, but unfortunately,
agent for every build, release, version, desktop mode: not all devices and browsers send UAProf
platform, device, whim, and vendor out headers. Additionally, a rather unpleasant
there? Mozilla/5.0 (Macintosh; percentage of the links to UAProfs are
not valid. And there is inconsistency in the
A: Pretty much.
U; Intel Mac OS X 10_5_7;
en-us) AppleWebKit/530.17 amount and quality of the data in the UAProf
files themselves.
Q: Does anything else send
(KHTML, like Gecko)
Q: OK, so, there are a million billion
Version/4.0 Safari/530.17
User-Agent headers besides
If that looks an awful lot like desktop OS user agents and UAProfs aren’t all
browsers?
X Safari, that’s because that user agent that reliable, yet you claim that there
is completely identical to one of the user
A: Several other kinds of applications
that make requests to web servers also
agents for desktop Safari.
is a sane and reasonable way to do
user-agent-based detection?
send User-Agent headers. These
include, but aren’t limited to, search engines,
Q: But if someone has gone to the A: In Chapter 5, we’ll be meeting some
trouble of disguising his mobile browser organizations and projects whose entire
crawlers, and various Internet bots (both
as a desktop one, shouldn’t we respect existence is concerned with tracking user
benign and nefarious). Sometimes web
his wishes and give him a desktop agents and building databases of metadata
server logs capture user‑agent information
experience? about them and other data sources like
about unusual things that are accessing
our sites, like a web viewer built into, say, a UAProfs. Until then, we’ll keep it simple
note‑taking desktop application, or a web
A: Though this is a delicate question of
philosophy, we tend to lean toward “yes,”
and use a basic server‑side script to look
bookmarking tool, or a monitoring service that for user‑agent strings that bear the primary
and fill in the gaps with responsive design hallmarks of mobile browser user agents.
pings a site to make sure it is operational.
(which will adapt to the environment no
Q: Why would people “spoof” their
matter who or what the browser claims to be,
assuming the browser is modern enough to
browser’s user agent?
support media queries and the like). There’s
a bit of a gray area in terms of whether users
A: Why would anyone purposely ask
their browser to “lie” for them, you ask?
know what they’re doing or not, but, hey, as
far as we’re concerned, you should get what
104 Chapter 3
www.it-ebooks.info
a separate mobile site
detectmobilebrowser.php.txt
This is the script!
The one you
download might
not look exactly The script might look a bit
Do this!
the same (it beastly right now, but we don’t
might be a newer have to do much to tame it.
version), but it When you first open up
Rename this file
should be similar. detectmobilebrowser.php in your preferred text editor, you
might find it a bit…brutal‑looking. But fear not. We’re redirect.php and save it
going to walk you through the basics of how it works, inside the chapter3 folder.
but, really, all you have to do to get it to work is make a
couple of small changes—and we’ll show you how.
106 Chapter 3
www.it-ebooks.info
a separate mobile site
redirect.php
108 Chapter 3
www.it-ebooks.info
a separate mobile site
Test Drive
Copy the contents of the 1 Put the contents of the chapter3 folder at the root of
chapter3 folder to your web your web server.
server's document root. If you don’t want to put the files at the document root, no biggie. Just be
sure to update the path in the line that defines $mobile_location.
index.php There’s no
need for PHP The mockup viewed on
processing in this an iPhone 4—simple,
file, so we’ll just but it works.
index_mobile. make it .html.
html
styles.css
The mobile mockups we’ll be using
throughout this chapter are just that—
mockups. They use sample data to
represent what the site will look like when “plugged into”
real data APIs. The data represented is imaginary, and
many links aren’t functional. Don’t worry about it!
110 Chapter 3
www.it-ebooks.info
a separate mobile site
Do this!
Let’s see how the mobile mockup looks in the Opera Mini 4.2 simulator. Use the web‑embedded
Opera Mini simulator to view the mockup at http://hf-mw.com/ch3/ex/1/.
Make some notes about what looks different (or, alas!, broken). Can you find at least four differences
between the way the mockup looks in the Opera Mini simulator versus the iPhone or Android
simulator (page 109)?
1 2
3 4
The mockup looks pretty different in Opera Mini 4.2, huh? Let’s look at some of
the places where it differs or is weird. We found five trouble spots.
Bonus points if
5
The status message uses overflow: you noticed this
on the iPhone or
scroll, which is an absolute no-no on all Android already!
mobile devices. Content is cut off, and
scrolling is not working.
Q: Why do I have to view this example on http://hf-mw.com? If you are doing your work on your own computer, you may well have
Why can’t I use my own copy? an IP address that is not visible to the entire Internet (a so‑called
internal IP address only visible to the network you are connected to).
A: Opera Mini is a proxy browser. That means that all web traffic
goes through an Opera server. So, the example mockup and other
If you are doing work on a hosting provider or otherwise have the
web pages for Creature Comforts on an externally accessible web
code bits have to be hosted somewhere that Opera’s servers can server, you can certainly use your own copy.
reach.
112 Chapter 3
www.it-ebooks.info
a separate mobile site
Ready Bake
DOCTYPE
Let’s convert the mockup page to be an XHTML‑MP document. Edit the
index_mobile.html file and replace the HTML5 DOCTYPE (top line of the
file) with the following two lines:
114 Chapter 3
www.it-ebooks.info
a separate mobile site
Q: Apparently I missed the memo. What’s a DOCTYPE? Q: So what’s the point of a DOCTYPE, and why do
browsers insist on them?
A: DOCTYPE
A (more formally, a document type
declaration) is a short piece of text at the top of SGML and XML A: Browsers perform a kind of “sniffing” (not too different
documents that informs the client (i.e., browser) which DTD to from our own user‑agent sniffing earlier) on DOCTYPEs.
evaluate the document against. While they don’t formally validate documents, they use the
DOCTYPE as a hint about what “mode” to assume and how to
Q: Too many acronyms. SGML and XML documents? render the content.
DTD? Remember the Opera Mini situation, wherein changing the
DOCTYPE from HTML5 to XHTML‑MP (or XHTML‑Basic)
A: HTML is descended from SGML (Standard Generalized
Markup Language), while XHTML is a kind of XML (and thus
caused the layout mode to change? That’s a good example of
this at work.
is more rigidly structured than its “X”‑less kin), so both warrant
DOCTYPEs. Other browsers use the DOCTYPE to determine whether to
render the content in “standards” mode or in “quirks” mode, a
Document type declarations (DTDs) are formalized definitions backward‑compatible, more tolerant mode.
of what elements (tags, attributes, etc.) are allowed, and where,
in the type of document they describe. Each specification of As of HTML5, all pretense of the browser going out and actually
HTML and XHTML has its own DTD. looking at a DTD has been dismissed, which is why one ends
up with the short and simple <!DOCTYPE html> (no URL
Nominally, associating a document with its intended DTD would to a DTD).
allow the rendering client to go validate the document against
that DTD. In real‑life web browsers, this doesn’t happen—web
browsers never actually go out and validate against DTDs.
116 Chapter 3
www.it-ebooks.info
a separate mobile site
XHTML-MP Exposed
This week’s interview:
Why bother with XHTML-MP
Grumpy Mobile Web Developer: You’re looking XHTML-MP 1.2: The entire XHTML‑MP lineage
a bit long in the tooth there, XHTML‑MP. How gives you the accesskey attribute on anchor (<a>)
long until you buy the proverbial farm, or sell it to tags. That lets you assign digits 0–9 as shortcut keys
HTML5? for those anchors. This can be very nice on phones
XHTML-MP 1.2: I’m not dead yet! Some people
that have numeric keypads. It can also help cut down
on tedious scrolling.
GMWD: So…XHTML‑MP invented access keys?
think I’ve been put out to pasture, but I’m a useful old
coot. I keep those older mobile browsers in line. You
XHTML-MP 1.2: Well, technically that was passed
can depend on me. I can help keep you out of trouble.
GMWD: What kinds of trouble can you keep me out down through generations, from WML through
of ? C‑HTML to us. It’s quite an heirloom.
XHTML-MP 1.2: You want examples? OK. What’s GMWD: WML? C‑HTML?
XHTML-MP 1.2: I’m not dead yet, but those guys
the point of having an anchor (<a>) tag with a
target of _new or _blank if you’re on a mobile
sure are. Wireless Markup Language (WML) is
device? Many mobile browsers won’t let you open a
gradually being phased out entirely. It’s quite different
new window from a link. So, I don’t support targets.
than HTML, and my family replaced it as the
Oh, and, frames—those are dangerous mojo. I don’t
preferred mobile markup variant.
support any frames, not even those fancy‑pants
iframes. C‑HTML (Compact HTML) was used a lot in Japan
118 Chapter 3
www.it-ebooks.info
a separate mobile site
Test Drive
1 Convert the document to XHTML-Basic.
Replace the current DOCTYPE tag with the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN"
"http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">
Q: So, I know we’re going all hardcore Q: Isn’t Opera Mini 4.2 pretty archaic? Q: But didn’t you just say that
simplified for now, but, after changing How many people really use that version smartphones are now outselling these
the DOCTYPE to XHTML-Basic, does anymore? dinosaur feature phones?
the mockup we looked at on page 115 still
work in Opera Mini 4.2? A: Admittedly, it’s not a recent browser.
But browsers of its vintage absolutely do
A: Outselling doesn’t mean outnumbering.
There are still vast numbers of existing
A: Yep! You can see this at http://hf-mw.com/
ch3/ex/2a if you are curious.
exist out there in the woolly wilds of Mobile
Web Land. It’s a good example of the sort of
older smartphones (not really “smart” by our
current standards) and feature phones. It will
browser with the sort of constraints one runs be some time before they disappear.
into on older feature phones in, especially,
emerging markets.
120 Chapter 3
www.it-ebooks.info
a separate mobile site
Ready Bake
Table Code
<table>
<thead>
<tr>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td><p>Message<br />Feb 3 8:54PM EST</p></td>
<td><p><a href="#">Supply Request #493-C4 Approved</a><br />
Hi, Jess, Good news! I wanted to let you know that we were successful in
tracking down those bottles...</p></td>
</tr>
<tr>
<td><p>Message<br />Feb 3 1:47PM EST</p></td>
<td><p><a href="#">Supply Request #493-C4 Received</a><br />
This is an automated message to confirm that your recent Supply Request
has been received and is in process...</p></td>
</tr>
<tr>
<td><p>Event Scheduled<br />Feb 3 8:22AM EST</p></td>
<td><p><a href="#">Itinerary 39924 Approved LAX -> DAC</a><br />
Your itinerary for event: "Bangladesh Flood Event" has been approved.
Your calendar has been updated...</p></td>
</tr>
<tr>
<td><p>Personnel Event<br />Feb 2 9:23PM EST</p></td>
<td><p><a href="#">Re: Personnel Confirmation 03/05 - 03/15</a><br />
Jessica! Thanks so much for committing to this operation! I think
Dr. Madling is going too and...</p>
</td>
</tr>
<tr>
<td colspan="2"><div class="morelink"><p><a href="#">More >> </p>
</a></div></td>
</tr>
</tbody>
</table>
Which elements are valid where? Use what we’ve learned and your own intuitive sense to figure
out which tags and attributes are OK in which standards. An element may be OK in more than one
standard!
XHTML-MP 1.2 XHTML-Basic 1.1 HTML5
<font>
<table>
<a target="">
<sup>
<a accesskey="">
<u>
<tbody>
<link>
<strong>
<video>
<iframe>
122 Chapter 3
www.it-ebooks.info
a separate mobile site
Mac
Windows
Chrome: ALT-[acces
skey] Certain operating system
[accesskey] shortcut keys or software
FireFox: ALT-SHIFT-
configurations could take
Linux precedence over these, so
your mileage may vary.
Get some validation
Remember how we told you that it’s important to use valid markup?
Let’s not just give that lip service—it’s time to validate the markup in the
mockup and make sure it’s up to snuff. Let’s head over to the invaluable
W3C Markup Validator site to check our code.
http://validator.w3.org
Uh oh!
124 Chapter 3
www.it-ebooks.info
a separate mobile site
Test Drive
Fix the markup problems in the index.html file.
<a target="">
<sup>
<a accesskey="">
<u>
<tbody>
<link>
<strong>
<video>
<iframe>
126 Chapter 3
www.it-ebooks.info
a separate mobile site
Mobile-savvy CSS
CSS Mobile Profile 2.0 (CSS‑MP) and XHTML‑Basic (or XHTML‑
MP) go together like peas and carrots. The CSS‑MP standard was
developed with low‑ to mid‑range phones in mind.
What do you get in CSS Mobile Profile? Well, most of what you’ve come
to expect out of CSS2, and even a bit of CSS3. But not everything.
Sounds complicated
and depressing. How am I
going to learn this stuff?
Buckle up. Roll up your sleeves. Batten down the hatches. We’re going to go on a journey here—a
journey that, if everything goes right, will end with a loving marriage between XHTML‑Basic and
CSS Mobile Profile. We’ll be editing both index.html and styles.css.
<head>
<title>Creature Comforts Agent Portal</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1,
maximum-scale=1" />
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
index.html
2 Let’s refactor styles.css to be valid CSS Mobile Profile.
The background-image
and background-repeat * {
properties are supported in padding: 0;
CSS‑MP, but having a big margin: 0;
header with a background }
image wastes a lot of space. body {
Let’s just get rid of the font-family: "Helvetica", "Arial", san-serif;
background image. font-size: 100%;
width: 100%;
background-color: #f3ffc2;
background-image: url('cows.jpg');
background-position values in background-repeat: no-repeat;
percentages and pixels are not background-position: 50% 0px;
supported in CSS-MP, so we’d }
p {
have to change this if we were font-size: .95em;
keeping the background image. margin: 0.25em 0;
}
so far is compliant…onward!
styles.css
128 Chapter 3
www.it-ebooks.info
a separate mobile site
h3 {
font-style: italic;
font-weight: 100;
font-size: 1.15em; styles.css
}
ol {
width: 100%;
}
a {
text-decoration: none;
color: #096c9f;
}
.header {
height: 150px;
}
#tools ol {
Since we last used this<ul> list-style-type: none;
CSS, we changed ourles }
to an <ol>. These ruted #tools ol li a {
will need to be upda
-webkit-border-radius: 5px;
to reflect that.
-moz-border-radius: 5px;
border-radius: 5px;
display: block;
height: 1.1em;
width: 94%;
background-color: #fff; These properties to
margin: 3%; create rounded corners
border: 1px solid #ccc; are invalid in CSS-MP,
text-align: center; and most of those older
padding: .6em 0; browsers don’t support
} them, anyway. Delete
.greeting {
border: 1px dashed #10508c;
these from the CSS.
border-width: 1px 0;
}
#dashboard {
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
background-color: #fff;
border: 1px solid #ccc;
margin: 1em 3%;
padding: .5em 0;
width: 94%;
}
<tr class="even">
<td class="event event_meta"><p><strong>Message</strong><br
/>
Feb 3 8:54PM EST</p>
</td>
Hey, hotshot! Apply <td class="event"><p><a href="#"><strong>Supply Request #493-
these classes to the o. C4 Approved</strong></a><br />
other three rows, to Hi, Jess, Good news! I wanted to let you know that we were
successful in tracking down those bottles...</p></td>
</tr>
But alternate
tr.even with tr.odd.
4 And now back to styles.css: adapt styles to apply to the
tabular markup. index.html
We switched from <div>s to tables for layout. We’ll want to get rid
of some properties that no longer make sense, and make a few edits to
others.
styles.css
130 Chapter 3
www.it-ebooks.info
a separate mobile site
styles.css
#status_message {
background-color: #f8f1b2;
padding: 0.25em;
line-height: 1.3em;
border: 1px solid #ccc;
border-width: 1px 0;
height: 70px;
And, finally, get overflow: scroll;
rid of these. }
styles.css
Hmmm…something is missing
Take a look at this screenshot from the Opera Mini 4.2 simulator of the
current mockup. Notice anything? We’ve lost the list numbering on our
<ol>—and those numbers indicated the access keys. Uh oh. How the mockup
currently looks:
Where’d the numbers go? no access keys.
The numbers are still “there,” but we’ve applied CSS that makes the
<li> elements look like buttons that span the full width of the window.
So the numbers are off to the left of the visible content.
Normally, to “bring them back,” we’d use something like:
#tools ol {
list-style-position: inside;
}
#tools ol {
margin: 0.5em 1.5em;
}
132 Chapter 3
www.it-ebooks.info
a separate mobile site
Test Drive
Change the CSS selectors in the styles.css file and convert the <ol> to a
<ul> in index.html. Don’t forget to add the access key numbers to the text
content of the links, too!
index.html
Great success!
It’s a big world, and there are billions (yep) of Some older mobile browsers (and current, lower‑end
mobile phones. Not all of them are bleeding‑edge mobile devices) implement different standards for
smartphones, and sometimes you have to make your HTML and CSS.
website or web app work with those phones.
XHTML Mobile Profile (XHTML‑MP) is a
There are real‑life circumstances: older systems, mobile‑specific standard used by many mobile
recalcitrant clients, or specific projects that make browsers. It is similar to XHTML, but does not support
having a totally separate mobile website necessary. everything that XHTML does.
One of the ways to route mobile traffic to a Similarly, CSS Mobile Profile (CSS‑MP) is a
mobile‑specific website is to use server-side mobile mobile‑specific flavor of CSS.
device detection and redirection.
XHTML‑MP was superseded by XHTML-Basic
User-agent sniffing is a popular technique for 1.1, which is almost the same except for a few new
evaluating whether an incoming request is from a supported elements.
mobile browser.
It’s important to choose the appropriate DOCTYPE
User‑agent sniffing examines the User-Agent for your mobile web project and pay attention to
header that browsers send as part of each HTTP keeping your markup valid—bad code can make
request. Users can “spoof” their user agent— phones behave very badly.
knowingly or not. This is a weakness of this method.
134 Chapter 3
www.it-ebooks.info
a separate mobile site
Q: There’s XHTML-Basic/XHTML-MP instead of HTML, Q: What happens if I just can’t get my site to do what I
and CSS-Mobile Profile instead of full-on CSS2. Is there an want in a way that is perfectly valid XHTML-Basic or CSS-MP
equivalent mobile flavor of JavaScript for mobile devices? or whatever? Does the sky fall? Do phones around the world
crash?
A: Yes, there is a mobile‑specific JavaScript called ECMAScript
Mobile Profile, but you can’t rely on it. We’ve worked with phones A: Being successful on the mobile web often means making
where the JavaScript cannot change anything on the page once it compromises and trade‑offs. While writing valid code is something to
is loaded, which means most of the things you use JavaScript for shoot for, it’s not always 100% feasible. But knowing the rules before
cannot be done. So if you’re targeting old phones, you’re probably you break them is always a good motto to live by.
better off not relying on JavaScript.
What devices
should we support?
Well, sure your
site doesn’t work on this
phone, but you could have left
out the part about “out-of-date
technophobe Luddites”...
Your
brain magic
Definition
of where
to draw
the line
138 Chapter 4
www.it-ebooks.info
deciding whom to support
140 Chapter 4
www.it-ebooks.info
deciding whom to support
142 Chapter 4
www.it-ebooks.info
deciding whom to support
Does your
mething
If you’re doing sone need to be seu rvice
ay ed to worry Online vs. offline or do you ne sed online,
intense, you m d, memory, and
about CPU spee CSS effects support offlied to
ne usage?
whether or not celerated.
are hardware ac
Audience usage
Hardware performance
What devices are
your customers most
likely to use?
Connection speed
Stakeholder devices
That video-intensive
think that
Did you really aw site will only work well
ay without
you could get tever phone on fast connections.
supporting whaens to use?
your boss happ
144 Chapter 4
www.it-ebooks.info
deciding whom to support
to ask!
r hurts
Analytics
e ve
It n
Geographic
Audience Trends
Survey
Big collections
the Device Anywlikhee
Device Data Explorer an re
Browserscope can d
some degree) at
(to
Income, age, anged nder Databases answer questions abhelp
which devices supp out
all impact wh is which features. ort
phone someone
likely to own.
Demographics
Example
Case Study
that allows
Mo Better Museums is building an app
eras at
museum visitors to point their phone cam
aining more
Time to put your magician’s hat on and work a piece of art and see an overlay cont
which piece
some magic. For each case study, build a information about the piece. It can tell
requirements list based on what the app is e’s location.
of art is being viewed based on the phon
trying to accomplish and the target audience. ty.
Phone reception in museums can be spot
The list should include must‑have
requirements and nice‑to‑have features.
Requirements:
• Must have: support JavaScript
Requiremen
ts :
Case Study
A politician wants an edge
in a
close election. She would
like an
app for volunteers to use
when
they go door‑to‑door to en
courage
people to vote. The app
will
provide the address of pe
ople to
contact—with a map if po
ssible—
and what questions the vol
unteer
should ask. Volunteers are
in
short supply, so she would
like the
app to support whatever
phone
they happen to own.
146 Chapter 4
www.it-ebooks.info
deciding whom to support
Study ticed an
Case s no P
Corp ha in India. The V lobal’s
Global s G
e in sale ould be
increas elieves India c like a localized
b ld e
of Sales arket. He wou t will work on th
m a
next big Global’s site th ia. He wants it
of Ind mers to
version lar phones in
s t p o p u s s ib le for custo
mo po
easy as ones.
to be as rs on their ph
r d e
place o
Require
m ents:
EXAMPLE
Case Study
that allows
Mo Better Museums is building an app
eras at
museum visitors to point their phone cam
aining more
a piece of art and see an overlay cont
which piece
Don’t you hate it when someone tells information about the piece. It can tell
you there is no right answer? Yeah, well, e’s location.
of art is being viewed based on the phon
sorry about that. There are no right ty.
answers when it comes to requirements. Phone reception in museums can be spot
Requiremen
ts :
Case Study • Must have: Internet
A politician wants an edge
in a
connection
close election. She would
like an
app for volunteers to use • Nice to have: ability
when to Nice! Some
they go door‑to‑door to en
courage display images for m opportunities
people to vote. The app ap
will for progressive
provide the address of pe
ople to
• Nice to have: Java enhancement!
contact—with a map if po
Script
ssible— for interactive maps
and what questions the vol
unteer
should ask. Volunteers are
in
short supply, so she would
like the
app to support whatever
phone
they happen to own.
148 Chapter 4
www.it-ebooks.info
deciding whom to support
Study ticed an
Case s no P
Corp ha in India. The V lobal’s
Global s G
e in sale ould be
increas elieves India c like a localized
b ld e
of Sales arket. He wou t will work on th
m a
next big Global’s site th ia. He wants it
of Ind mers to
version lar phones in
s t p o p u s s ib le for custo
mo po
easy as ones.
to be as rs on their ph
r d e
place o
Iteration helps you
uncover extra
requirements.
Require
If you were to pull
m ents
• Must have: su :
back the curtain on most mobile
projects, you’d find that the people who
pport basic ma
for old phones rkup made the site were uncertain about what
devices they needed to support. They
• Must have: H made the best guess they could and then
TTPS for che
ckout iterated on it until they perfected the site.
• Must have: c
ookies for login
Every project draws the line somewhere on which Progressive enhancement should be the default
devices it supports. approach. This will make your site work on many
more devices than you can officially support.
Knowing where to draw the line is a combination of
experience, research, and gut instinct. Unless you know for certain that you cannot
support a device, you shouldn’t exclude it. New
There is a difference between devices you don’t
browsers show up all the time. Give them a chance
support and those you can’t support because
to prove they’re up to snuff.
they lack critical features that make it impossible to
use your site. Don’t let mobile’s complexity overwhelm you. You
already have all of the tools you need to know
Look at your project requirements and your target
where to draw the line. Trust your experience
audience to help decide where to draw the line.
and instincts.
150 Chapter 4
www.it-ebooks.info
Setting the bar for the devices we support doesn’t take care
of a few nagging issues. How do we find out enough stuff about our users’
mobile browsers to know if they measure up before we deliver content to them? How do
we avoid only building (lame) content for the lowest common denominator? And how do
we organize all of this stuff so that we don’t lose our minds? In this chapter, we’ll enter
the realm of device capabilities, learn to access them with a device database, and,
finally, discover how to group them into device classes so that we can keep our sanity.
152 Chapter 5
www.it-ebooks.info
device databases and classes
Device database
contains data about Software API helps to findsea
devices and their match in the device databa
characteristics. for the current user agent.
Information is available
about the device’s hardware, A successful match gives
access to all sorts of da us
platform, and browser. ta
about the device.
154 Chapter 5
www.it-ebooks.info
device databases and classes
Meet WURFL
WURFL (Wireless Universal Resource FiLe, usually A device is not a platform is
pronounced “wuhr‑full”) is an open source device not a browser.
database with an enormous amount of information
There is no good word meaning “a
about the specific capabilities of mobile devices and
device’s hardware characteristics
their browsers.
combined with its platform and
Recently, the longtime maintainers of the WURFL OS melded with its browser.” There really
project started a company called ScientiaMobile to maybe should be. WURFL’s notion of a device
provide commercial support for WURFL. is a combination of all three, and contains
information about hardware, OS, and browser.
WURFL tracks details about mobile device specifics
from ringtone formats to physical screen sizes. Terminology makes it difficult to be clear. We’re
guilty, too, so keep in mind that our use of the
Not all of WURFL’s capabilities are of interest to
shorthand word device likely carries some of
us web developers, but you’ll find some real, useful
the connotations of browser, hardware, and OS.
gems in there.
1 Go to http://www.tera-wurfl.com/explore in a
mobile browser.
156 Chapter 5
www.it-ebooks.info
device databases and classes
Q: What is ScientiaMobile? Q: What APIs are there for WURFL other than the
PHP API?
A: ScientiaMobile is a company founded in 2011 by Steve
Kamerman, Luca Passani, and Krishna Guda. Luca has A: ScientiaMobile provides Java, .NET, and Database APIs
been one of the maintainers of the open source WURFL in addition to PHP.
project since he and Andrea Trasatti started WURFL in 2001.
Steve created Tera‑WURFL, which has become the WURFL
Database Edition.
Q: How does WURFL data get updated? More to the
point, how would I get new data as it’s updated?
Q: Is WURFL free? Do I have to pay for it? A: ScientiaMobile keeps an eye out for new devices.
Sometimes manufacturers provide information directly. Other
A: It depends. WURFL is technically open source. The
WURFL API is available under the Affero General Public
times, people using WURFL submit the information. A large
part of the work any device database vendor does is related
License v3 (AGPL), which is an open source license. The to validating information provided about new devices.
WURFL XML database has a restricted license that only
allows it to be used with the WURFL API. Q: Who decides what capabilities get tracked by
So, if you can comply with the AGPL restrictions, you don’t WURFL?
have to pay anything. But AGPL is more aggressive than its
GPL cousin. With AGPL, running the software on a server
counts as a distribution, which triggers provisions requiring
A: ScientiaMobile picks capabilities based on suggestions
from the community.
you to open source any derivative work.
If AGPL doesn’t work for you (and, in many cases, it probably
Q: Where is this WURFL community of which you
won’t), ScientiaMobile will sell you a commercial license. speak?
Q: If I integrate WURFL with (insert your favorite open A: The community is a mailing list. WURFL has been
around so long that the list is called the WML programming
source solution here) and build a site on top of it, do I
have to open source the whole site? list. There are also conversations happening in the support
forums on ScientiaMobile.com.
A: Short answer: buy a commercial license or talk to a
lawyer. ScientiaMobile.com also has a licensing FAQ.
Q: Are there other things out there that do what WURFL You can find the wml-program ming
does? list at http://tech.group s.ya hoo .com/
group/wmlprogramming/.
A: Yes. WURFL is the only device database that offers
an open source license, but there are several commercial
databases. Device Atlas is probably the best known
alternative. Others include Mobile Aware and Detect Right.
158 Chapter 5
www.it-ebooks.info
device databases and classes
A tree of devices and their families One way it finds matches is by using matchers
optimized for a given family of browsers or
As the WURFL API analyzes a given user‑agent string, a devices. The most recent PHP API has a few dozen
series of increasingly generic fallbacks is evaluated, with handlers to deal with the analysis of user agents.
the goal of at least slotting the device into the correct The API first determines which handler makes the
family of related devices. most sense for the given user agent. User agents
with the string “BlackBerry,” for example, are
You can think of WURFL’s data as a sort of tree of handed off to the BlackBerryHandler.
devices, with the trunk being a generic browser and each
branch, twig, and leaf a more specific device or group of Each handler is savvy about the kinds of
differences that matter for user agents in its
devices. The API tries to get as far as it can toward the
family, which cuts down on the amount of
exact leaf, but has the rest of the tree to fall back on if it super-specific user agents that WURFL data
cannot. maintainers have to track.
Additionally, the WURFL data for a given device only The PHP WURFL API combines handlers with RIS
defines the capabilities for that device (or group of devices) matching (reduction-in-string—that is, removing
that differ from its parent device or devices. That way, pieces of an unrecognized user-agent string until
the WURFL XML data file is kept reasonably small (a it ends up with one it does recognize) to get to its
bit under 10 MB as of mid‑2011), despite the amount of end result.
information it really contains.
Organize the capability data. Build a page and output the data
in an HTML table.
160 Chapter 5
www.it-ebooks.info
device databases and classes
chapter5
The configuration file will tell
the explore code where to find
your WURFL installation.
explore
We’ll be editing this Your WURFL
file and renaming it to installation
remove the .example.
config.php.example
This file holds some
code that gets WURFL resources
WURFL device
information and WURFL PHP
organizes it. device.php API code WURFL data source
Simple stylesheet
for our page.
styles.css
You’ve got WURFL installed (we sure hope), but now we need to configure it to work
in the web page we’re building. To do that, we’ll want to create a configuration file.
Open config.php.example in a text editor. Make edits to the paths below as indicated, and
then save the file as config.php in the explore folder (remove the .example extension!).
Organize the capability data. Build a page and output the data in an
HTML table.
162 Chapter 5
www.it-ebooks.info
device databases and classes
OK! We’ve got our configuration file. Now we need to create some code that will
initialize WURFL stuff and get it all warmed up so that we can plumb its depths for
device capabilities. Open device.php in your text editor. It’s rather empty to start with,
so let’s plop in some WURFL‑y code!
device.php’s job is twofold: initialize WURFL objects using the User-Agent header
of the current request (that is, the user’s browser) and to organize the capability data
for the device into something we can display on a page.
This includes our new
config file.
<?php
require_once('config.php');
$user_agent = $_SERVER['HTTP_USER_AGENT'];
device.php
I’m OK with most of this,
but I can’t seem to get my
head around what those last
lines of code do.
Let’s take a slightly closer look at the last line of the boilerplate code chunk from page
163. It’s where we tell WURFL how to build a device object. In our case, we’re using
$user_agent, which currently holds the value of the User-Agent header of the
requesting client.
That is, we’re instructing WURFL to take the user‑agent string of the current user’s
browser and try to find a match in its data file. If it’s successful, we’ll have a device
object containing the capabilities of the browser and device.
$device = $wurflManager->getDeviceForUserAgent($user_agent);
At this point, if
The getDeviceForUserAgent method in the WURFL_WURFLManager class things went right,
takes a user‑agent string and returns the matching device (from WURFL data) as a the device capabilities
WURFL_CustomDevice object. are ready to use.
Translation: We feed it a user-agent
string, and it gives us a device object
populated with values for the various
capabilities.
Organize the capability data. Build a page and output the data in an
HTML table.
Now that we have a populated
WURFL device object, let’s
organize the device’s
capabilities so that we can
display them in an HTML table.
164 Chapter 5
www.it-ebooks.info
device databases and classes
$device = $wurflManager->getDeviceForUserAgent($user_agent);
if ($device) {
$groups = $wurflManager->getListOfGroups();
$grouped_capabilities = array();
foreach($groups as $a_group) {
$grouped_capabilities[$a_group] = array();
$capabilities = $wurflManager->getCapabilitiesNameForGroup($a_group);
foreach ($capabilities as $cap) {
$grouped_capabilities[$a_group][$cap] = $device->getCapability($cap);
}
}
}
This code chunk organizes the This is how we access the values device.php
capabilities of the current device of individual capabilities. We’ll look
and browser into groups. more closely at this in a bit.
We’re done with device.php for now. Time to edit index.php and add some code.
Organize the capability data. Build a page and output the data in an
HTML table.
166 Chapter 5
www.it-ebooks.info
device databases and classes
A good start!
You can see all of the capabilities of your desktop browser now, with
capabilities organized by group.
Organize the capability data. Build a page and output the data in an
HTML table.
<div id="testform">
<form method="post" action="<?php print $_SERVER['PHP_SELF']; ?>"
id="useragentform">
<p>Test this user agent string:</p>
<input type="text" name="useragent" id="useragent_field"
value="<?php print $user_agent; ?>" /><br />
<input type="submit" name="submit" value="Test User Agent" id="submit" />
</form>
</div>
require_once('config.php');
$user_agent = (isset($_POST['useragent'])) ? $_POST['useragent'] :
$_SERVER['HTTP_USER_AGENT'];
$wurflConfig = new WURFL_Configuration_XmlConfig($wurflConfigFile);
168 Chapter 5
www.it-ebooks.info
device databases and classes
Test Drive
1 Save all of the changes and load up the
index.php file in a web browser.
The first time you load the page, you should see your
own browser’s WURFL capabilities.
I’m up to my ears
in capabilities. How can I do
something useful with them?
Steps to success
170 Chapter 5
www.it-ebooks.info
device databases and classes
button.png
$value = $device->getCapability($capability_name);
WURFL
A WURFL CustomDevice object, configuration
already initialized and populated. We’ll do this in the device.php
file in just a sec. config.php
A couple of examples:
Is this a mobile device? WURFL device
$value = $device->getCapability('is_wireless_device');
initialization
and testing
device.php
$value = $device->getCapability('cookie_support');
Want to see info about all the WURFL directory and file structure
capabilities? Check out http://wurfl.
sourceforge.net/help_doc.php.
you are here 4 171
www.it-ebooks.info
ask wurfl
$wurflManager = $wurflManagerFactory->create();
$device = $wurflManager->getDeviceForHttpRequest($_SERVER);
$device = $wurflManager->getDeviceForHttpRequest($_SERVER);
$is_phone = $device->getCapability('is_wireless_device');
device.php
Yeah, right?
172 Chapter 5
www.it-ebooks.info
device databases and classes
<div id="content">
For requests that qualify as mobile
<h1>I'm Freaking Out!</h1>
(per the is_wireless_device_capability),
index.php
<?php if ($is_phone): ?>
<div id="panic_button">
show the panic button…
<img src="button.png" alt="HELP!" /> …othe
</div>
rwise, just show the phone
number, real big (via a CSS sty le).
<?php else: ?>
<h2>Help is only a phone call away.</h2>
<div id="big_number">
503-555-2939
</div>
<?php endif; ?>
<p>Pre-test late-night jitters? A math problem that just
won't budge? Our expert on-call tutors are standing by to help
you through tough moments.</p>
</div>
Test Drive
Make the changes from pages 171 and 173 to config.php and index.php, save the
files, and then view the resulting I’m Freaking Out! page in a desktop browser
and a mobile browser.
The button on a
mobile device
174 Chapter 5
www.it-ebooks.info
device databases and classes
WURFL Exposed
This week’s interview:
What’s the use of WURFL
Interviewer: So, WURFL, what exactly did you bring Interviewer: Great. The button doesn’t make sense on
to the table here? iPod Touches. Now we’re back to square one.
WURFL: Seems pretty clear. You can tell right off if the WURFL: No, no. Like I said, you’re not using me to my
browser is mobile! full potential. Dig deep and revisit my capabilities. I think
Interviewer: There are other ways to do that, you
you’ll make a nice discovery or two.
know. Client‑side detection, basic server‑side detection— Interviewer: But you have over 500 capabilities! How
WURFL: Basic mobile‑or‑not‑mobile is sort of child’s
will I find the right one?
play. You’re not using me to my full potential. WURFL: You’re complaining because I’m too
Interviewer: All right, try me.
comprehensive? I can’t win! Fine, I’ll give you a hint:
176 Chapter 5
www.it-ebooks.info
device databases and classes
$phone_string = $device->getCapability('xhtml_make_phone_call_string');
$is_phone = false;
if ($has_radio === 'true' && $phone_string && $phone_string !== 'none') {
$is_phone = true;
}
device.php
Q: Don’t mobile phone browsers Q: How come there has to be that Q: So, we think a browser that has a
automatically recognize phone numbers pop-up confirmation box after a user non-none value for xhtml_make_
and link them for you? clicks on a phone call link? Why can’t it phone_call_string is on a
just spawn a call directly? mobile phone that can make phone calls,
A: Most do, yep. But a couple things about
that. Most relevant to our present situation: A: This is to protect the user from being
but do we know?
No more button on
iPod Touch! But still
there on iPhone!
178 Chapter 5
www.it-ebooks.info
device databases and classes
Jim: This could get out of hand! In a more complex project—or even
AcedIt!’s site, if it adds more mobile bells and whistles—it seems like using
scattered, individual WURFL capabilities all over the code would cause a
lot of headache and mess. I mean, if we end up with one capability being
tested for in one template, another capability being tested somewhere else…
and so on.…
Frank: I agree. It seems like we’d be delivering a slightly different website
to every possible combination of capabilities—a nightmare to think
through and test.
Jim: A one‑way ticket to spaghetti code, yeah.
Frank: But I don’t want to throw out the whole concept. Even though I
like to try to do feature detection on the client, and we still want to make
our stuff as responsive as possible, it does seem like a device database like
WURFL can give us insight into some details that we might not be able to
get from other sources.
Jim: But how do we corral all of this so it doesn’t make us crazy?
Frank: It seems like if we could group devices logically—instead of testing
capabilities piecemeal—we might be able to keep our sanity. Remember
how we recently spent time thinking through how to evaluate which devices
to support by picking and choosing features and drawing the line for
phones that don’t make the cut?
Jim: Do I ever. I’m still somewhat cross‑eyed from those exercises!
Frank: It seems like we could go one step further and create buckets of
devices that are within the group of devices we decide to support.
Jim: Interesting…I think you might be on to something.
After updating device.php with the changes from page 173 with the stuff on
page 177, you might realize that you don’t have an iPod Touch on hand to
test the changes.
To see what an iPod Touch would see, edit the device.php file. Use
the getDeviceForUserAgent() method instead of the
You can find one getDeviceForHTTPRequest() method and give it an iPod
on page 175. Touch user agent.
Herding devices
A device class creates a sort of logical corral into which
you can herd devices that have certain things in common.
Just as a rancher might put spotted cattle into one field, A device class is an abstract
collection of common
giant work horses in another, and little piglets in yet
another (can you tell we’ve never been ranchers?), we can
sort our devices into virtual cubby‑holes with device classes.
characteristics that define
Sort once, then go
Once our rancher identifies an animal as belonging to
a group of devices (and
one of those three groups, he can make further decisions
without having to look at the smaller details. He can feed
their browsers).
oats to the horses without stopping to reverify that they
have legs of a certain length or swishy tails or can support
PNG images (everyone knows that horses lack support for
transparent PNGs!).
He already knows they’re horses because they’re in the
horse corral. He doesn’t have to tailor feeding to each
individual animal (that would be a lot of horse meals to
keep track of). But, at the same time, he doesn’t feed oats
to the piglets.
You can test what content gets delivered for a given device or browser by using its user agent
when intializing the WURFL device.
$wurflManager = $wurflManagerFactory->create();
$device = $wurflManager->getDeviceForHttpRequest($_SERVER);
$user_agent = "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_2 like Mac
OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2
Mobile/8H7 Safari/6533.18.5";
$device = $wurflManager->getDeviceForUserAgent($user_agent);
device.php
180 Chapter 5
www.it-ebooks.info
device databases and classes
Device classes
As we learned earlier, we can run incoming requests against
a device database to get device information. By grouping the
capabilities and values that matter for the site at hand, we can
adapt content across an entire device class instead of chasing
down each individual capability’s value.
These device class definitions, converted into code, sort
devices into one of several groups. Once our devices are
sorted, we can take action without having to keep track of each
individual constituent capability.
Desktop-like devices
Spiffy, newer
smartphones
AcedIt!’s web
folks sent this
early mockup of
Users can shop online the new site’s
and study now—use home page.
interactive products
right on the site itself.
AcedIt! will feature These ads are
products in a snazzy for related
Flash movie. services, like paper
proofreading and
local study groups.
The home page has
excerpts from the
company’s blog.
182 Chapter 5
www.it-ebooks.info
device databases and classes
Interactive
pieces of the A fuller mobile experience
site look best on By creating a device class that encompasses the requirements
screens at least for the richer mobile experience, we can design something neat
320 pixels wide. without risking poor support on lesser devices.
By specifying that devices in this class must have a WebKit‑
based browser, we can use CSS goodies like gradients with
relative confidence. We can also rely on a certain level of decent
JavaScript support.
simpler_mobile
184 Chapter 5
www.it-ebooks.info
device databases and classes
have the f
super‑nifty, touch‑driven interface for their online products.
It’s not done yet, but they want to be prepared for its .”
eventual launch by being able to identify tablets now. “supported
ort
Where to draw the line - SSL supp
pport
- Cookie su a S c ript support
It’s important to the AcedIt! folks that their visitors can
som e J a v
either shop online or use the online products. If visitors
- At least 6px
can’t do either because of device constraints, the device
lu t io n o f at least 17
and browser they are using are considered unsupported. - A reso
The company’s ecommerce software requires cookie
support and a bit of JavaScript support (not nearly
as much as the online interactive products). It is also
mandatory that, for security, devices support SSL.
simpler_mobile
higher_mobile
Yep, tablets
Hey, desktop is a
device class, too!
tablet
unsupported
Slightly Confused Web Developer: I’m SCWD: OK, so we have a desktop device class,
having trouble getting my head around this device which is self‑evident…and that tablet device class,
class business. A collection of capabilities…tied to which has minor differences…let’s see. What are
an experience? the differences between higher_mobile and
Device Class: I admit, I am a bit difficult to
simpler_mobile?
capture. If I were a painting, I’d be an abstract blur. Device Class: As we know that
I’m a concept, a way to think about organizing higher_mobile represents devices with larger
common things so that we can create just a few screens and capable WebKit‑based browsers,
flavors of a site, instead of a million billion. we can be more confident that they have the
SCWD: So, a device class is a set of WURFL
horsepower to handle some of the site’s more
intensely interactive features.
capabilities—
Device Class: Not so fast. Remember that I’m
simpler_mobile, by contrast, represents
devices with narrower screens and perhaps less
an abstract concept. We’ll be using WURFL here,
cutting‑edge browsers. We can give them smaller
but there’s no reason you have to. No reason, in
images (yay! less bandwidth). We know they support
fact, you have to use any device database.
SCWD: This is all starting to feel a bit woo‑woo.
a bit of the ol’ JavaScript, but can give them a dose
of content that is less deluxe.
SCWD: Wait, how do we know that the
Can you help me understand where the rubber
meets the road here?
simpler_mobile devices support JavaScript?
Device Class: OK. Let’s plan this together. For
Device Class: We will test for at least a modicum
AcedIt!, we’ll have five device classes.
SCWD: Does that mean we’ll be making a version
of JavaScript support. Devices that don’t have the
ability to modify the DOM after page load will be
of the website for each? That sounds like a big task. shunted off into the unsupported device class.
Device Class: No, we only need to focus on SCWD: So what’s up next to keep this ball rolling?
Device Class: We need to map the right
the differences. For example, until the new touch‑
based, tablet‑optimized flashcard interface is
WURFL capabilities and their values to the
launched, the tablet‑device‑class version of the site
device classes we want to create. After we have
only differs from the desktop version in that no
a logical representation of the device classes, we’ll
Flash content will be used.
create code to do some actual testing and slotting.
186 Chapter 5
www.it-ebooks.info
device databases and classes
Pool Puzzle
Time to find the right WURFL capabilities
and values for our device classes.
Your job is to take the WURFL
capabilities and values from the
pool and place them into the blank
device classes. You may not use
the same item more than once.
higher_mobile
desktop
tablet
lesser_mobile
resolution_width
>= 320 pixels
mobile_browser =
'Safari' OR 'Android'
higher_mobile
is_wireless_devi
ce = false
e
= tru
blet
is_ta
desktop resolution_width
< 320 pixels
false
tablet _support =
https is_wireless_devi
ce = true
dom = false
ajax_manipulate_
cookie_support =
false
lesser_mobile
resolution_width
< 176
unsupported
188 Chapter 5
www.it-ebooks.info
device databases and classes
Q: Why the focus on WebKit-based browsers? Are the Q: What’s with the names higher_mobile and
devs hating on other, totally decent mobile browsers? simpler_mobile? Is there a naming convention I
need to know about?
A: WebKit‑based browsers are seen by many mobile web
devs as both fairly advanced and consistent. Browsers with A: Eh, we just pulled those out of a hat. They sounded
the WebKit rendering engine generally have good support for about right. We used underscores simply so we can translate
HTML5, JavaScript, and CSS3. the names into code more easily. You can call your device
classes whatever you’d like. Within reason.
Note the word generally in the previous sentence. The problem
is, there is a misconception as to just how consistent browsers
based on WebKit are. The sad truth is: there’s still a lot of chaos. Q: Now that we’ve got device classes, I can never test
an individual device capability?
Mobile platform strategist Peter‑Paul Koch spells out the
pitfalls of assuming consistency in mobile WebKit browsers
in the thorough post “There is no WebKit on Mobile” on his
A: You can totally still test individual capabilities. In fact, the
solution for the panic button problem was very appropriate: we
QuirksBlog (http://bit.ly/uWnFLa).
were testing for the value of a very specific capability—a value
that might differ among devices in the same device class (an
Q: If mobile WebKit isn’t really a “thing,” why are we iPhone versus an iPod Touch, for example).
basing a device class on it?
Q: If I use device classes in a project, will I always have A: Not at all! Content and layout adaptation is a concern
that spans the entire Web. The mobile web doesn’t have a
five?
monopoly on that.
A: Nope. You might have 10, 4, or 0. Having fewer means
less complexity. Having more means more nuance. Q: OK, great. I have some circles with some
capabilities and required values in them. Now what?
But, first…
Find the device_classes folder in chapter5, and then the test_classes
device_classes folder beneath it. Eureka! This is our playground for now.
This is probably starting to feel pretty familiar: we need to set up
a configuration file so that WURFL can be initialized. Start by
test_classes
copying the config.php file from the panic_button folder into
device_classes/test_classes.
config.php
To cut down on busywork, we
cobbled this together for you.
And we’re off!
device.php Here’s what we’re going to do:
We’ll add to this file over
the next few pages. Write a (PHP) function to test the individual
device capabilities we care about in each device
device_classes.php
class definition.
190 Chapter 5
www.it-ebooks.info
device databases and classes
This function
default:
returns a TRUE or
return FALSE;
FALSE (Boolean)
}
result—whether
}
192 Chapter 5
www.it-ebooks.info
device databases and classes
We wrote that matching function for you, but now it’s time for you to do a bit of work.
Which tests belong to which device class?
We’ve got these tests sorted! Now it’s time to convert them into grouped nuggets of real PHP
code. Keep truckin’!
194 Chapter 5
www.it-ebooks.info
device databases and classes
Comfortable with PHP code? See if you can plunk in the missing
pieces of the code chunk here. These are the device class tests,
grouped and ready to go.
$device_class = NULL;
196 Chapter 5
www.it-ebooks.info
device databases and classes
Test Drive
1 Put code into the device_classes.php file. Mozilla/5.0 (PlayBook; U;
Add the tests from page 196 into the file after the RIM Tablet OS 1.0.0; en-
device_match function and save it. US) AppleWebKit/534.8+ (KHTML,
like Gecko) Version/0.0.1
Safari/534.8+
2 View the index.php file in a browser.
By default, the page will show you the device class
assigned to your current browser. PantechP2020/JIUS05172010R;
Mozilla/5.0 (Profile/MIDP-2.0
Configuration/CLDC-1.1; Opera
3 Test some different user agents.
Mini/att/4.2.19039; U; en-US)
Enter the user agents here into the form field to see
Opera 9.50
which device class they get assigned to.
BlackBerry8330/4.5.0.77 Profile/
MIDP-2.0 Configuration/CLDC-1.1
VendorID/105
BlackBerry9300/5.0.0.794
Profile/MIDP-2.1 Configuration/
CLDC-1.1 VendorID/245
Each option is totally valid. We have to decide which seems most ideal for the
AcedIt! study aid website.
198 Chapter 5
www.it-ebooks.info
device databases and classes
Joe: Do we really need to add yet another device class? Seems like a
lot to wrangle.
Frank: I agree. We need to strike a balance between nuance and
the number of device classes we have. It feels like we already have
about the right number.
Joe: So, what now?
Frank: OK. The problem is that higher‑resolution devices that
don’t have WebKit browsers are falling through and not getting
assigned to any device classes—
Joe: Aren’t there actually two problems here? One, we’re not
thinking through what experience those devices should get, like you
said. But we also don’t have a fallback, default device class overall.
Seems possible something could go wrong with device detection or
there might be something else we’re not thinking of. I think we need
a sort of safety net device class.
Frank: Good point. For the first problem, if we’re not adding a
new device class, we need to fill the gap. The question is: what is
more relevant here, device resolution or browser capabilities?
Joe: AcedIt! puts a lot of focus on the interactive elements of the
site—that suggests browser capabilities matter more. But at the
same time, we were planning on delivering smaller images to those
lower‑resolution devices.
Frank: I think you’re right about AcedIt!’s priorities. How about
this for a compromise? We update the device classes such that there
isn’t a top‑end resolution restriction on the simpler_mobile
class.
That does mean that some higher‑resolution devices get a
simpler feel, but if I recall correctly, the dev team working on
the touch‑optimized flashcards is using a framework targeted to
WebKit‑based browsers. Heh, in fact, I think that’s why we were
testing for WebKit browsers in our higher_mobile class in the
first place. Wow, I need to get more sleep; my memory is failing me.
Joe: What about images?
Frank: I think we’d do fairly well if we gave all mobile devices
mobile‑optimized images that aren’t any bigger than 320 pixels in
any dimension. Then we can use responsive image techniques to get
us through the final mile on the device.
$device_class = 'higher_mobile';
}
else if (device_match('is_wireless_device', '===', 'true') &&
device_match('resolution_width', '<', '320')) {
Careful: Only
$device_class = 'simpler_mobile';
remove one of the
}
parentheses here.
else {
$device_class = 'desktop';
}
Add a fallback
default device class. device_classes.php
Test Drive
Make the changes to the device_classes.php file and retry the user‑agent strings from
page 197 in the test form.
200 Chapter 5
www.it-ebooks.info
device databases and classes
The starting point of index.php has all versions of the content (for all device
classes) in it. It’s time to identify which pieces of content will be delivered
(or not delivered) to users who fall into our different device classes. For each
number below, find the corresponding markup on the right and fill in the
blanks with the appropriate device classe(es).
202 Chapter 5
www.it-ebooks.info
device databases and classes
Here’s the markup from the index.php file. Use it to answer the questions on the
page at left.
Oh, you thought you were done? At least you’re halfway there!
11 Hide the link to the interactive flashcards for the device class.
204 Chapter 5
www.it-ebooks.info
device databases and classes
<p>Morbi non erat non ipsum pharetra tempus. Donec orci. Proin in ante.
Pellentesque sit amet purus. Cras egestas diam sed ante. Etiam imperdiet
urna sit amet risus...</p>
</div>
<div id="feature">
<div id="featured_product">
7 <p>Featured product Flash slideshow.</p> It’s probably obvious, but these
are just placeholders until thet
8 <p>Static featured product image.</p> Flash movie and static varian
</div> are developed.
</div>
<div id="ads">
... We removed a bit of the tex
</div> content to save space here ont
9 <div id="fromtheblog"> this page.
...
</div>
<div id="navigation">
<ul>
10 <li><a href="#">Home</a></li>
<li><a href="#">Shop Online</a></li>
<li><a href="#">Study Now!</a></li>
<li><a href="#">Blog</a></li> 11
<li><a href="#">Contact Us</a></li>
<li><a href="#">FAQ</a></li>
</ul>
</div>
<div id="footer">
<p>Current device class: <?php print $device_class; ?></p>
</div>
</body>
</html>
Time to look at the markup differences for the different device classes and
convert our decisions into code.
4 Use this stylesheet for the higher_mobile device class. Everyone gets the aptly named
common.css.
<link rel="stylesheet" type="text/css" href="../assets/common.css" />
<?php if ($device_class == 'desktop'
|| $device_class == 'tablet'
2 || $device_class == 'unsupported'): ?>
<link rel="stylesheet" type="text/css" href="../assets/desktop.css" />
<?php endif; ?> There are elements common to both
<?php if ($device_class == 'higher_mobile' mobile device classes in these styles.
3 || $device_class == 'simpler_mobile'): ?>
<link rel="stylesheet" type="text/css" href="../assets/mobile.css" />
<?php endif; ?>
<?php if ($device_class == 'higher_mobile'): ?>
4 <link rel="stylesheet" type="text/css" href="../assets/mwebkit.css" />
<?php endif; ?>
206 Chapter 5
www.it-ebooks.info
device databases and classes
6 Do not show these two links for the unsupported device class.
and
We’re not showing ads on the mobile layouts,, we’ll
instead of having blog teas ers on the page
provide a link to the blog subpage.
9 Don’t show these sections on the higher_mobile or simpler_mobile device classes.
208 Chapter 5
www.it-ebooks.info
device databases and classes
Test Drive
Try it out! Find the finished version of index.php in index_solution.php.
Replace the current index.php file with index_solution.php.
Navigate to test.php in your web browser and try some of the user‑agent
strings from the useful_user_agents.txt file to see the different device class
versions. Hit index.php directly with your desktop browser to see the desktop
version of the mockup.
Go back to the explore page we created earlier in the chapter and enter the
Do this! following user agent: facebookexternalhit/1.1 (+http://
www.facebook.com/externalhit_uatext.php).
210 Chapter 5
www.it-ebooks.info
device databases and classes
generic
Detail of our explore page. The ver
values for the display group are m. y
generic—we shouldn’t rely on the
A stitch in time
The PHP API provides a few methods for determining how
specific a match was. Let’s take a peek.
If there is no
device ID at all…
if (!$device->id
|| (!$device->isSpecific()
&& $device->fallBack === 'root')) {
/* FAIL--make sure you have a plan for this situation */
}
212 Chapter 5
www.it-ebooks.info
device databases and classes
Q: What is this desktop browser patch of which you Q: Wouldn’t the device class testing code be better as
speak? a function/object/whatever?
Q: I don’t understand what parts of WURFL are the Q: Excuse me, but if I am not mistaken, the
API parts. $device variable is global. That’s stinky.
A: WURFL itself is just the data. The API is all the code
that interacts with it, organizes it, and so on. There are APIs
A: See above.
Update device_classes.php in the adapt_content directory to include a test for generic IDs or
lookup failures. Assign the unsupported device class in this case.
$device_class = NULL;
Hint: Code will
go in this area. if (device_match('is_wireless_device', '===', 'false')) {
$device_class = 'desktop';
}
device_classes.php
$device_class = NULL;
if (!$device->id ||
(!$device->isSpecific() && $device->fallBack === 'root')) {
$device_class = 'unsupported';
}
else if (device_match('is_wireless_device', '===', 'false')) {
$device_class = 'desktop';
}
device_classes.php
Congratulations, you’ve
mastered wrangling device
capabilities and classes.
It’s a complex concept—and you made it! You even have
a content‑adapted web page to prove it. Good work!
214 Chapter 5
www.it-ebooks.info
device databases and classes
Device data repositories like WURFL (Wireless Device classes are abstract groupings of devices based
Universal Resource FiLe) allow us to get at very detailed on common capabilities.
information about a whole lot of devices. By slotting a device into a device class, we can take
WURFL data contains over 500 capabilities per device, further action upon it (e.g., delivering adapted content)
organized into a couple dozen groups. without having to track individual capabilities constantly.
We can use a device database to identify a value for a It’s important to build in default device classes, error
given capability and act upon that value. checking, and generic device handling into any code
that uses a device database for identification.
WURFL’s PHP API is one of several APIs for interacting
with WURFL data. Different APIs handle and represent Like nearly everything on the Web, server‑side device
the data slightly differently. detection is not a 100% bulletproof concept.
ScientiaMobile was founded in 2011 by some of the Server-side detection and content adaptation can be
original WURFL maintainers. The company provides married with client-side adaptation—the two are not
open source and commercial licenses for WURFL. There mutually exclusive. We’ll be looking into this more later.
are alternatives if WURFL doesn’t work for you.
When working on larger projects, it can be helpful to
group relevant capabilities into device classes.
The Tartanator
HTML5, CSS3, JavaScript,
mobile frameworks…They
sure don’t make tartans like
they used to.
“We want an app! Just a year or two ago, that hallmark cry generally meant
one thing: native code development and deployment for each platform you wanted
to support. But native isn’t the only game in town. These days, web-based apps for
mobile browsers have some street cred—especially now that hip cat HTML5 and
his sidekicks, CSS3 and JavaScript, are in the house. Let’s dip our toes into the
mobile web app world by taking a mobile framework—code tools designed to help
you get your job done quickly—for a spin!
218 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
ever seen on t
super‑swanky JavaScript, and CSS3 goodness—in short, the core pieces for
building modern, interactive web applications.
Which is, well,
a bit misleading.
request
web
page
S ur
e, h ere
server
you go . CSS
HTML
images
JS tc.
e
The server returns the pa
The downside to this—especially when it comes to
and all the assets needed ge
mobile devices with limited concurrent HTTP requests,
load it correctly. to
bandwidth, and processing power—is that it means
requesting and downloading assets the browser may
already have downloaded before, and encumbers the
browser with re‑rendering content and reprocessing code
that might not have changed. It also feels less interactive.
Subsequent requests
mits,
Subsequent requests via form sub d a b
it more information.
e
client
clicked links, etc . In
e
request
web
page
S ur
e, h ere
server
you go . CSS
HTML
images
JS tc.
Certain assets (images, data, e
JS) can be saved locally for The first request gets all the
later or offline use. various components of the page…
…and often some special
instructions about which
assets to cache.
Subsequent requests
requests (AJAX)
Often asynchronous
it more information.
ed a b
client
e
In
request
data
S ur
e, h ere
server
you go .
Response content A response can be limited to the
be inserted into ancan specific content needed, avoiding
existing page’s DOM. the bandwidth and processor
costs of a full-page reload.
App?
ite!
New Webs eessag
- Make it so
u
see and explo sers can
Welcome m out Us
tartan patt re the
…link to Ab
About Us page Keep t h is s im p le e
their phones. rns right on
ore info…
A history of Tartan page for m
nts Lots of images
Tartan eve
s Unlimited.
Links to informatio not of tartans!
the history of tart
n about
a v e s o m e ideas here… - Wouldn’t it
Ih le! b e
ans. are possib users could c c ool if
sure if they own tartans? re a te their
This content isn’t Bug Pat Ewan
ready yet. about th
is. Tartans!
This is the main part of th
e Can this b
e done?
Events page idea…sounds like an app? - A collection
popular “tra of tartans:
d
- It would be nice if the app
or! as well as ne itional” ones
nat
The Tarta
could somehow “link into” our w-world and
user-create
international events database. d tartans.
the whole or”?
Maybe call t
he Tartana
- Could a user’s phone help app/site “T g!
rin
find the nearest events? Has a nice
ait until
- Might want to w
3 of the site
phase 2 or phase
mplex?
for events stuff—co
222 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
Jill: Hey guys, I know the requirements are pretty vague. When I
talked to Ewan, I got the sense that there are two main things he wants
to accomplish with the site…or app, or whatever. There’s a chunk
of content pages: info about the organization and education about
tartans. Then there’s this whole section he’s calling the Tartanator—
Joe: The Tartanator? Seriously? Heh.
Jill: Yeah. Actually, it seems he wants to call the whole site that, not
just one section. Anyway, it seems like it’s sort of a combination of a
browsable listing of tartan patterns to explore and, he hopes, a way for
users to create their own tartan patterns using a form—
Frank: Wow. That sounds simultaneously bizarre and daunting, but
possibly fun as an implementation challenge.
Joe: OK, content pages, Tartanator area…what about this note about
an Events page?
Jill: Hold your horses! I’m getting there! We’ve decided to do this
project in two rough phases. For the first phase, we’ll build basic
structure for the content pages and implement the tartan listing. He’d
also like us to think about how an interface for users to create their own
tartans would look, and maybe prototype the frontend of that.
Joe: So, like, we’d build the form for creating a tartan, but it doesn’t
need to do anything yet?
Some of the tartan
will be in the Tartansatth at Jill: Something like that, yes. In phase 2, we’ll make it actually work,
tartan directory or ’s and we’ll also come back and work on an Events section.
Frank: OK, sounds like we need to go start building a mobile web app.
MacAlpine clan
tartan
Innes clan
tartan Lennox clan
tartan
224 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
Depending on
mobile web apps—can be a daunting proposition. A web development
framework—that is, a packaged collection of interactive elements and code
226 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
Q: Are there other mobile frameworks out there? Q: Do we really need to use a framework?
A: And how! There are more every day. Some other mobile web
frameworks include Sencha Touch, Wink, iUI, DHTMLX Touch, and
A: Do we need to? Technically? No, not at all! In fact, we
encourage you to build applike mobile websites from scratch, if that’s
JQTouch. your bag.
the mobile experience. Some frameworks also include a server‑side We have limited time and space here, folks. Trying to pull off what
component to help generate (as opposed to adapt) content. we need to do for the Tartanator without a framework of any sort
would be pretty hairy, not to mention the chaos of extra testing that
Q: Wait. What about zepto.js or XUI? would be required (as we wouldn’t have that underpinning of tested
cross‑platform support).
A: Zepto.js (very lightweight JavaScript, with jQuery syntax) and
XUI (also very compact JS) both fall more on the library side of the Q: I still don’t get it. How is the Tartanator an app instead of
line (versus framework). Frameworks tend to have UI components, a website?
while libraries tend to be code—in this case, JavaScript—only. This
is a grey area; the division between library and framework isn’t easy
to define.
A: Because Ewan says so. No, really. The subtleties of
differentiation between app and site are so vague that the answer
sometimes seems almost arbitrary.
Q: So, jQuery Mobile is a mobile version of the original Ewan has a vision of the Tartanator as a functional, web‑based
jQuery library? thing. His focus is on the ability to find and create tartans, and, also,
ultimately, to search for relevant events. In his mind, that makes this
A: Not so fast, hotshot! jQuery Mobile builds on top of jQuery. It
does not replace it. You’ll notice that when we start building stuff with
an app.
jQuery Mobile, the first JavaScript file we include is the core jQuery
library.
Q: But what if it were a site? I couldn’t use jQuery Mobile
then, right?
Q: So, jQuery Mobile is a JavaScript development framework A: jQuery Mobile is a user interface framework. It doesn’t care
that extends jQuery. whether you call what you’re making with it an app or a site. Its job
is to make things feel usable and not break across various mobile
A: Bear with us. Yes, there is JavaScript in the jQuery Mobile
framework. But jQuery Mobile is not a JavaScript framework. It’s
platforms, using a combination of CSS, JavaScript, and HTML5.
bigger than that. It’s a user interface framework. That means it also
includes stylesheets, icons, and other pieces of the puzzle.
Q: But which mobile browsers support HTML5?
index.html
</head>
<body>
<h1>The Tartanator</h1>
228 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
Hmmm…the footer
text doesn’t quite fit…
but let’s worry about
that a bit later.
230 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
index.html
Time to add a navigation‑like list of links to the three subpages. Edit index.html and add a
very simple <ul> after the introductory paragraph inside of the main content <div>. The
text of the list elements should be the names of the subpages: About Us, Find an Event,
and Popular Tartans.
index.html
</div><!-- /content -->
<ul data-role="listview">
232 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
et="true">
<ul data-role="listview" data-ins
index.html
There is no tartan.html
file in our main directory
yet. This is how jQuery
Mobile reacts when it
encounters a broken link.
234 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
Head First: I hear you have something to tell us jQuery Mobile: There are several points, if you’d
about what a “page” really is, to you. let me finish!
jQuery Mobile: I do! It’s one of my favorite things Instead of requesting and downloading the whole
about myself, so I wanted to explain. requested page—scripts, images, styles—and
reinitializing and rebuilding the DOM from scratch,
Remember how the structure of one of my pages
I only snag the pieces that matter. That saves on
uses a <div> with a data-role value of page?
Head First: Sure.
HTTP requests, bandwidth, and processing time
and makes the experience feel a bit more natural
jQuery Mobile: The markup contained within that
and native.
<div>—often a header, content area, and footer—is Head First: If content pieces are loaded
what I consider a page. dynamically, how come I see the URL of the link I
Head First: Then what is the point of the rest of
clicked on in the address bar of my desktop browser?
the HTML markup? Is it chopped liver? jQuery Mobile: My modest exterior belies the deep
jQuery Mobile: Definitely not! In a web app
sophistication of my navigation model. I always aim
to have real URLs for the pages in my apps, even if
designed along my principles, each HTML file is a
the pages are really generated dynamically or there
standalone, autonomous thing that you can visit in
are multiple <div> tags with a data-role of
your browser.
page in a single HTML document.
Head First: I’m lost. If each HTML file is
independent, why bother with the <div> with the By having a unique and reusable URL for AJAX‑
data-role of page? loaded content chunks, I can make them look and
jQuery Mobile: Let me back up. When you first
act like full‑blown web pages. When the browser
allows me to (not all browsers do), I even update the
navigate to a page in one of my sites or applications,
displayed URL in the browser’s address bar as I load
that page is loaded just like any old HTML page on
in new content asynchronously.
Head First: If I understand correctly, then, I can
the Web.
But once that first page is loaded, I do something
access each HTML file in my app or site directly,
different. When you click on links, I find the page
but the content of those documents can be retrieved
content from the requested HTML document—that
independently and dynamically, when linked to, to
is, the stuff in the <div> with the data-role of
improve performance and responsiveness?
page—with AJAX and inject it into the current
page’s DOM— jQuery Mobile: Exactly!
Head First: But what is the point of that? Head First: Thanks, jQuery Mobile, for a really
dynamic chat.
Q: If pages are loaded with AJAX, why Q: How did jQuery Mobile know which Q: What version of jQuery Mobile are
do I need to create separate pages at all? data-* attributes to use? Where can I we using?
Can’t I just put all of my app’s content find information about all of the available
into one page and use jQuery Mobile to
show and hide it?
data-* attributes? A: The jQuery Mobile dev team is on a tear!
During the time we spent writing this chapter,
236 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
Footer (RE-)Construction
As we saw on page 230, the text in the page footer is getting truncated on narrow screens.
That’s because jQuery Mobile leaves room for button placement around header elements
in headers and footers—but we don’t have any buttons in our footer. Let’s fix it!
<div data-role="footer">
<h4>Bring forrit the tartan!</h4>
</div><!-- /footer -->
index.html
Footer (RE-)Construction
index.html
4 Check our progress.
Save the file and view index.html in a smartphone browser or
simulator.
238 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
index.html
That’s it! The footer should
look a lot better now. Try
saving your changes and
reviewing our improved
footer in a mobile browser
The release of jQuery Mobile 1.0
or simulator.
includes a new Theme Roller tool that
makes theming jQM easier. See more at
http://jquerymobile.com/themeroller/.
240 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
tartans.html
tartans/baird.html
<li><a href="tartans/abercrombie.html">
<img src="tartans/icons/abercrombie.png" alt="Abercrombie" />
<h3>Abercrombie</h3>
</a></li>
Add thumbnails to the list items in tartans.html. The icons are in the tartans/icons directory and
have the same name as their HTML counterparts (but with a .png extension).
<ul data-role="listview">
<li><a href="tartans/abercrombie.html">
<img src="tartans/icons/abercrombie.png" alt="Abercrombie" />
<h3>Abercrombie</h3>
</a></li>
<li><a href="tartans/arbuthnot.html">
<img src="tartans/icons/arbuthnot.png" alt="Arbuthnot" />
<h3>Arbuthnot</h3>
</a></li>
<li><a href="tartans/baird.html">
<img src="tartans/icons/baird.png" alt="Baird" />
<h3>Baird</h3>
</a></li>
<li><a href="tartans/barclay-dress.html">
<img src="tartans/icons/barclay-dress.png" alt="Barclay Dress" />
<h3>Barclay Dress</h3>
</a></li>
<li><a href="tartans/barclay.html">
<img src="tartans/icons/barclay.png" alt="Barclay" />
<h3>Barclay</h3>
</a></li>
<li><a href="tartans/birrell.html">
<img src="tartans/icons/birrell.png" alt="Birrell" />
<h3>Birrell</h3>
</a></li>
<li><a href="tartans/blair.html">
<img src="tartans/icons/blair.png" alt="Blair" />
<h3>Blair</h3>
</a></li>
<li><a href="tartans/borthwick-dress.html">
<img src="tartans/icons/borthwick-dress.png" alt="Borthwick Dress" />
<h3>Borthwick Dress</h3>
</a></li>
<li><a href="tartans/borthwick.html">
<img src="tartans/icons/borthwick.png" alt="Borthwick" />
<h3>Borthwick</h3>
</a></li>
<li><a href="tartans/bruce.html">
<img src="tartans/icons/bruce.png" alt="Bruce" />
<h3>Bruce</h3>
</a></li>
<li><a href="tartans/buchanan.html">
<img src="tartans/icons/buchanan.png" alt="Buchanan" />
<h3>Buchanan</h3>
</a></li>
</ul>
242 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
tartans.html
Test Drive
Give the <ul> in tartans.html a filter field and list dividers.
Add list dividers for each letter (except those that don’t
have any tartans, like Q and X).
Save your work and view the results in a browser. Pretty cool, eh?
244 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
Q: I notice that when you change Q: Will this stuff work on every Q: What happens if a device or
pages in a jQuery Mobile web app, there phone? browser isn’t supported? Or if JavaScript
is an animation effect. What is that? is turned off?
Before we start into the form, let’s check with the client to
make sure our overall approach so far is OK.
Hmmm…it’s…nice,
but can you make
it feel more…like a
native app?
246 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
Jim: What does “make it look like a native app” even mean?
Frank: It seems like that’s a very subjective thing, doesn’t it? I
think what Ewan is looking for is something that feels a bit more
“app”‑y.
Jim: Which means…?
Frank: I guess like tab bars, navigation elements, button‑y and
icon‑y bits. Ewan seemed happy with the transitions, for example.
Those, to him, feel native.
Jim: But don’t we run the risk of emulating one platform too
much at the expense of others?
Frank: Heh, yes. When people say “native,” sometimes they
are dangerously close to meaning “make it look like iOS, please.”
Each platform has its own UI metaphors.
Jim: This sounds like a catch‑22. To make our customer happy,
we need to look native, which might well mean alienating, say, our
Android and BlackBerry users.
Frank: I think we need to pick and choose some things we could
enhance to make the Tartanator feel more like an app without
making it look like an iPhone app. To be fair, jQuery Mobile
elements in their default skins look kind of iOS style. So we’re
already partway down this path.
Jim: So the aim is to make the Tartanator feel more like an app
without necessarily feeling platform‑specific native?
Frank: Exactly. I’ll sketch down a few thoughts on some changes
we can make to shoot for that goal.
A head
er that
sticks a
round
pp!
More like an a with a
ep la ce cu rren t <ul> of linksatever
-R h
bar/navbar/w
Tabs/
b persistent toolm of the screen.
utton
s inst at the botto
ead o e
f link h icons for th
s - Buttons witfeel more like an app.
toolbar will
What about the A eader stick
bou t Us page? - Make the h
around, too.
- Recent email fr
content isn’t pannom Ewan:
as well as he’d hopeing out
d.
- Maybe conflate
page and the Abo the landing Make Tartanator feel more applike: to-dos
into one? Use the ut Us page
as the info page? landing page
Convert links on landing page into persistent
toolbar with icons.
Do away with the separate About Us page, as
content is not forthcoming. Consider the current
landing page the de facto About page for now.
248 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
Construct a navbar
Inside of a header or footer container—so designated by the
data-role attribute—we can put another <div> with a
data-role of navbar. This tells jQuery Mobile to treat the Notice that we’ve
contents as buttons in a toolbar. The basic construction looks removed the
like this: data-theme attribute.
A data-role of navbar
triggers jQuery Mobile <div data-role="footer" data-position="fixed">
to make this look like, <div data-role="navbar">
well, a navbar.
</div><!-- /navbar -->
</div><!-- /footer -->
Navbar buttons (i.e.,
links) will go in here.
index.html
Put buttons in the navbar
Instead of links in a vertically organized list, we’re going to make
toolbar buttons to access the main sections of the Tartanator.
This is a more applike metaphor.
Remember, we’re
jQuery Mobile will automatically convert linked list elements jettisoning the
within a navbar into buttons. aboutus.html page
in favor of using
the index.html
<div data-role="footer" data-position="fixed"> page as an About
<div data-role="navbar"> page.
<ul>
<li><a href="index.html">About</a></li>
<li><a href="findevent.html">Events</a></li>
<li><a href="tartans.html">Tartans</a></li>
jQuery Mobile will </ul>
automatically make </div><!-- /navbar -->
these links look </div><!-- /footer -->
like buttons.
index.html
index.html
<ul>
<li><a href="index.html" data-icon="info" class="ui-btn-active">About</a></li>
<li><a href="findevent.html" data-icon="star">Events</a></li>
<li><a href="tartans.html" data-icon="grid">Tartans</a></li>
</ul>
index.html
250 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
index.html
Test Drive
Ah, iterative design. The way of the Web. Let’s update the Tartanator.
That’s looking
more like an app!
252 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
Size
Color
(Stitches)
Each ingredient in the
pattern is a pairing of a
color and a size. Black 6
Green 72
Blue 56
Red 4
Blue 4
Yellow 6
The Carmichael
Follow the tartan recipe clan tartan.
To weave the tartan, the pattern is followed in order (in our case,
we’ll be “weaving” with pixels instead of wool).
For Carmichael, 6 stitches of black are followed by 72 stitches of
green, followed by 56 blue, and so on. The first and last colors (black
When the last color in the pattern is reached (six stitches of yellow, and yellow) don’t repeat. In
in our example), the pattern is followed in reverse (blue, red, blue, tartan-ese, these are called
green). When the first color (black) is reached again, the cycle repeats. “pivots” in the pattern.
The pattern is woven both horizontally and vertically (warp and weft)
to create the overall tartan pattern.
4 blue
6 black 4 red
72 green 56 blue 6 yellow
254 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
Form structure
These are the things our
We’ll want users to name their tartans and, optionally, form needs to collect.
enter a description. Then, they can define color‑size
combinations to build the pattern itself. Let’s give our
form two main sections: a top section for metadata about
the tartan and a main section for defining colors and sizes.
<div data-role="content">
<form id="tartanator_form">
<ul data-role="listview" id="tartanator_form_list">
<li data-role="list-divider">Tell us about your tartan</li>
<li data-role="list-divider">Build your colors</li>
</ul>
</form>
</div><!-- /content -->
256 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
Ready Bake
<li data-role="list-divider">Tell us about your tartan</li>
<li data-role="fieldcontain">
Form Fields
<label for="tartan_name">Tartan Name</label>
<input type="text" name="name" id="tartan_name"
placeholder="Tartan Name" />
</li>
<li data-role="fieldcontain">
<label for="tartan_info">Tartan Info</label>
<textarea cols="40" rows="8" name="tartan_info"
id="tartan_info" placeholder="Optional tartan description
or info"></textarea>
</li>
<li data-role="list-divider">Build your colors</li>
build.php
Q: Why are we not assigning the Q: I’m confused. Which kind of Q: Do I need PHP for this part of the
data-role of fieldcontain element should I be assigning the project?
class to this <li>? It has fields in it.
A:
fieldcontain data-role
attribute to? Yep! As we move into the more
A: Each of these <li>s (li.
A: Whichever element contains the
functional pieces of the Tartanator, we’ll be
using PHP to do the crunching and thinking.
) will actually contain two
field itself—its immediate parent. That
colorset
fields. When we build the fields themselves,
we’ll place each one of them within its could be an <li> or a <div> or a
own <div>, and we’ll assign the <fieldset> or a <p> (or whatnot).
fieldcontain data-role to that The fieldcontain data-role
<div>. tells jQuery Mobile to group the contained
field and its label when enhancing the
form. So, each containing element with a
data-role of fieldcontain
should contain one field (and its label).
258 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
<li class="colorset">
<div data-role="fieldcontain" class="color-input">
<label class="select" for="color-<?php print $i ?>">
Color</label> Recall that we’re
<select name="colors[]" id="color-<?php print $i ?>" > inside a PHP loop;
<option value="">Select a Color</option> this assigns each field
<option value="#000000">Black</option> a unique ID.
<option value="#ffffff">White</option>
</select>
</div>
</li>
build.php
</select>
</div>
Tartan patterns <div data-role="fieldcontain" class="size-input">
can only have <label for="size-<?php print $i ?>">Stitch Count</label>
stitch counts <input id="size-<?php print $i ?>" type="range" min="2"
in multiples of step="2" max="72" autocomplete="off" name="sizes[]" value="2" />
2. The step </div>
attribute should </li>
be able to help
us here.
build.php
260 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
Test Drive
Time to put it all together and build our mobile‑looking (if not‑yet‑functional) form.
tartans.html
The ui-btn-right class will Assign the “b” theming
make the button float swatch to make the button
right (instead of left, stand out a bit more.
which is the default).
build.php
262 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
Test Drive
1 Link to the form from tartans.html.
Add the Create button to the header in tartans.html.
y M o b i l e H e lp
jQuer the surface
scratched
We’ve barely e things you can do
of all of th Mobile in this chapter.
with jQuery
lea rn mo re or find more f we’ve
To
rm ation ab out the stuf entation
info r to the doc
um
covered, refe ymobile.com. It’s very
on www.jquer
detailed.
People want apps! The definition of what, exactly, makes There are lots of mobile web frameworks out there
a website a web app is fuzzy. Applike websites tend (more every day!), representing many different
to feel more interactive than content pages. Chunks of approaches and emphases.
content and data are often retrieved asynchronously and
jQuery Mobile is a popular mobile web framework.
inserted into an existing DOM, reducing the frequency of
It has a strong relationship with well‑formed HTML5
full‑page loads.
markup, which makes it relatively straightforward to build
HTML5 is a specific, single thing—it’s a spec mobile interfaces from basic code.
representing the evolution of HyperText Markup
We built the structure for phase 1 of the Tartanator by,
Language (HTML)—but the term HTML5 is often used
among other things, using jQuery Mobile–enhanced
to represent a combination of technologies that create
listviews, headers, footers, navbars, and form elements.
applike web experiences.
Making a web app feel more native is always a
Building mobile web apps from scratch can be very
balancing act, requiring some careful decisions.
complex. We encourage you to try it! But for our
purposes, we used a mobile user interface development We used some HTML5 form element attributes to
framework to help us out. build our prototype form. jQuery Mobile helps to adapt
these form elements across mobile browsers, including
adaptation for those that don’t support them yet.
264 Chapter 6
www.it-ebooks.info
build a mobile web app using a framework
Q: How much of the code in the Q: Colors as a select list—that Q: The header and footer blink
Tartanator so far is really HTML5? doesn’t seem like the most fantastic sometimes, or are slower to load
That is, how much of it uses tags or user experience. than the other parts of the page.
attributes that are new as part of the Sometimes scrolling feels a bit slow.
HTML5 spec? A: When we enhance the form in
Chapter 7, we’ll add some JavaScript
Why is that?
Congratulations,
you’ve just built a
mobile web app with
HTML5 and its friends.
See? It’s really not too many steps from
the HTML and CSS you already know to
a mobile‑feeling, applike website!
The mobile web feels like that gifted kid in the class.
You know, kind of fascinating, capable of amazing things, but also a
mysterious, unpredictable troublemaker. We’ve tried to keep its hyperactive
genius in check by being mindful of constraints and establishing boundaries,
but now it’s time to capitalize on some of the mobile web’s natural talents.
We can use progressive enhancement to spruce up the interface in more
precocious browsers and transform erratic connectivity from a burden to a
feature by crafting a thoughtful offline mode. And we can get at the essence
of mobility by using geolocation. Let’s go make this a super mobile web app!
It looks nice…
Now that we’re done with phase 1, the Tartanator has that
mobile‑web‑app sheen.
268 Chapter 7
www.it-ebooks.info
mobile apps in the real world
We've got a
straightforward structure
based on HTML5—now
it's time to take it to the
next level!
…but it needs to walk the walk
Phase 2 will build on the stuff we’ve put in place, turning our
solid—but admittedly somewhat functionality‑free—web app into
what we think of as a super mobile app!
Geolocation
Progressive enhancement
Offline mode
270 Chapter 7
www.it-ebooks.info
mobile apps in the real world
App?
ite!
New Webs eessag
- Make it so
u
see and explo sers can
Welcome m out Us
tartan patt re the
…link to Ab
About Us page Keep t h is s im p le e
their phones. rns right on
ore info...
A history of Tartan page for m
nts Lots of images
Tartan eve
s Unlimited.
Links to informatio ot
n about v e s o m e id eas here…n - Wouldn’t it
of tartans!
the history of tart I ha le! b e
ans. are possib users could c c ool if
sure if they own tartans? re a te their
This content isn’t Bug Pat
ready yet. about th
is. Tartans! Ewan
This is the main part of th
e Can this b
e done?
Events page idea…sounds like an app? - A collection
popular “tra of tartans:
d
- It would be nice if the app
or! as well as ne itional” ones
nat
The Tarta
could somehow “link into” our w-world and
user-create
international events database. d tartans.
the whole or”?
Maybe call t
he Tartana
- Could a user’s phone help app/site “T g!
rin
find the nearest events? Has a nice
ait until
- Might want to w
of the site
phase 2 or phase 3
mplex?
for events stuff—co
The major objectives for the second phase of the project really
fall into two core goals:
1 Plug in the pieces that let users generate their own tartans.
We’ve got our prototyped form. Now we need to walk the walk and plug in the
pieces to make this actually work. We also need to enhance the existing form to
make it more usable for fancier smartphones and add a few bells and whistles.
App?
ite!
New Webs eessag
- Make it so
u
see and explo sers can
Welcome m out Us
tartan patt re the
…link to Ab
About Us page Keep t h is s im p le e
their phones. rns right on
ore info…
A history of Tartan page for m
nts Lots of images
Tartan eve
s Unlimited.
Links to informatio not of tartans!
n
the history of tart about a v e s o m e ideas here… - Wouldn’t it
Ih le! b e
ans. are possib users could c c ool if
sure if they own tartans? re a te their
This content isn’t Bug Pat
ready yet. about th
is. Tartans!
This is the main part of th
e Can this b
p? e done?
Events page idea…sounds like an ap - A collection
popular “tra of tartans:
d
- It would be nice if the app
tor! as well as ne itional” ones
na
The Tarta
could somehow “link into” our w-world and
user-create
international events database. d tartans.
the whole or”?
Maybe call t
he Tartana
- Could a user’s phone help app/site “T g!
rin
find the nearest events? Has a nice
ait until
- Might want to w
3 of the site
phase 2 or phase
mplex?
for events stuff—co
272 Chapter 7
www.it-ebooks.info
mobile apps in the real world
Frank: That first big requirement is a doozy, isn’t it? I think it’ll help
to break it down into smaller chunks.
Jim: Before we do that—what happened to the outstanding item for
the About Us page and historical background?
Frank: Oh, right! The wife of the guy who writes bios and
informational copy for Tartans Unlimited just had a baby. The new
father has found himself far busier than he expected and isn’t going to
be able to help out with the project for a while. Big surprise, huh? So
we’re not on the hook for that one right now.
Jim: Well, that’s one less thing, I guess. Let’s talk about getting the
pieces in place to allow users to create their own tartan patterns.
Not to brag, but I’ve already got a head start on this one. I’ve been
tinkering with a bit of JavaScript to enhance the form.
Joe: Cool. That’ll look nice and pretty. But we also need to drop in
server‑side scripts to do the actual work—
Jim: You server‑side guys! Trust me, enhancing the form interface is a
really significant improvement.
Joe: Anyway, I’ve been working on the PHP scripts. What about the
events stuff ?
Jim: Actually, is it OK if we focus on getting the tartan generation
nailed and circle back on the events searching when we’re feeling
ready to think about it? I only have room in my brain for so much at
one time.
Frank: I guess that’s fine as long as we get cracking on the custom
user tartans stuff right quick. We’re on a pretty tight timeline.
To-dos: custom user tartan pattern implementation Here's our master to-do
list for the custom
tartans requirement.
We'll start here!
Enhance the form we built to take advantage of capabilities of newer
mobile browsers.
Make sure the offline experience for this part of the app is acceptable.
274 Chapter 7
www.it-ebooks.info
mobile apps in the real world
The remaining
color-size When the range input
field pair changes value, a function
makes sure the stitch
count is an even number.
When a user clicks the Add
This Color button, the This is our workaround
color-size combo is added for jQM's lack of support
to the list. for the step attribute on
Color-size list range input fields.
ul#colorlist
Clicking an item
already in the
list removes it.
Enhanced build.php
form (detail) Our form's submit button
Take it for a spin
The button becomes
Hey, good news. You don’t have to do visible once at least one
anything to get the frontend enhancements color-size combo has
to work. It’s already done for you. Remember, the form is on been added to the list.
The starting point of the code in the the build.php pag
e.
chapter7 folder already includes the Also, we haven't “hooked up”
JavaScript enhancements. Go try it out! the backend yet; clicking
See how it feels in a mobile browser. this won't do anything yet!
276 Chapter 7
www.it-ebooks.info
mobile apps in the real world
onStitchSizeChange() Refreshes the <ul> and <li> elements pageinit and change
of the current color list. (color select field)
pagecreate
setColorSelectStyle() Makes sure the size value is an even integer.
Drop in server‑side code for processing the form and generating Next up!
resources (images, HTML, etc.) for user‑created tartans.
Make sure the offline experience for this part of the app is acceptable.
SOlUTion
onStitchSizeChange() Refreshes the <ul> and <li> elements pageinit and change
of the current color list. (color select field)
pagecreate
setColorSelectStyle() Makes sure the size value is an even integer.
278 Chapter 7
www.it-ebooks.info
mobile apps in the real world
Head First: OK, I gotta ask. We just did a whirlwind Head First: You’ve overridden the rendering of a
tour of a bunch of jQuery Mobile–specific JavaScript native form element. The color select field is now
interface enhancements. Was it really worth it? using a custom jQuery Mobile widget. Isn’t that kind
Interface Enhancement: What jQuery Mobile
of taboo?
makes possible, quickly, with respect to enhancing the Enhancement: It’s true that messing with native
mobile interface is compelling, sure, but I get your form controls is a bit controversial. I don’t argue for it
drift. Really, I’m trying to illustrate a broader concept as a general rule. However, in our particular case, the
here. styling necessary to give visual clues to the user—color
Head First: Which is?
swatches—wasn’t possible with traditional select fields.
chapter7
generate.php image.php config.php inc
css
extras
Using the data posted from
the form, generate.php
creates several resources.
findevent.php
generate.php
index.php
js
280 Chapter 7
www.it-ebooks.info
mobile apps in the real world
Asynchronous request
with XHR In this method, there’s never
a full-page reload. The
POST data
content of the new tartan
new tartan page is inserted into the
HTML URL DOM of the build page.
build.php generate.php
<new-tartan>.html
tartans.php
Q: Help! Something’s not working right! Q: About that XML. What the heck is that?
Q: How does the tartan list page work? A: Nah. It’s just something we started calling mobile web
apps that seem like they take good advantage of the neat things
mobile devices and their browsers have to offer.
A: The list.php file included in the page looks at the current
HTML files in the tartans/ directory to generate its list. For each,
it grabs its associated XML file (in tartans/data/) to get further
information, like the pretty display name. It then outputs an
<li> for each tartan, with a link to the tartan’s HTML page.
282 Chapter 7
www.it-ebooks.info
mobile apps in the real world
Make sure the offline experience for this part of the app is acceptable.
Offline is important
Part of giving a good experience to your users is making
your websites and apps behave when there isn’t an Internet
connection to be had.
For the Tartanator, we need to step back and figure out how
we can make things work better for our disconnected users.
We need to make certain things available offline.
How do we control
what’s available offline?
Is that even possible?
Make it manifest
Application cache is part of the HTML5 specification. It allows for control
over which web resources are cached for offline availability through the use of
a cache manifest.
A cache manifest is a specific type of file on a web server that gives instructions
about how or whether certain web resources should be cached on a user’s
device. By creating a cache manifest, we can dictate which things are available
offline for the Tartanator web app.
Browsers that implement application cache—or appCache, as it is almost
universally shortened to—also provide the window.applicationCache
object and its various events, which we can access and manipulate with
JavaScript if we like.
Support for appCache is fairly widespread in current browsers, with the
notable exceptions of Internet Explorer 9 and Opera Mini. Using a cache
manifest won’t cause problems for these browsers; they just won’t pay
attention to it.
284 Chapter 7
www.it-ebooks.info
mobile apps in the real world
e
The file must have a content-ittyp
Add a manifest attribute to the <html> tag of the applicable
2
pages with a URL (relative is fine) to the manifest file.
of text/cache- ma nifest , or
3 Make sure the manifest is served as the correct type of file. won't work.
manifest.appcache
2
Next, you update your web page(s) by adding a <!DOCTYPE html>
manifest attribute pointing to that file. You also <html manifest="manifest.appcache">
need to make sure the file is served as the correct <head>
Content-type (aka MIME-type). You can often
do this simply with Apache by adding the following
to the Apache configuration file or, more likely, an 3
.htaccess file on your website’s filesystem.
AddType text/cache-manifest .appcache
This line tells the web server to
serve files ending in .appcache as the
text/cache-manifest content type. The file has to be of this type, .htaccess
or browsers won't recognize it.
Safari's developer
tools look almost
exactly the same. It can be easy to get yourself in a jam working
with cache manifests.
Cache manifest behavior can be tough and confusing to
debug, and malformed cache manifest files are difficult to
find and remove without the right tools. We recommend
It can be a bit painful using either Chrome or Safari for building and testing our Tartanator
to try to excise poorly cache manifest. Also note that appCache isn’t supported by Internet
formed appCaches from Explorer before version 10, which at the time of this writing is still in
mobile devices. developer preview.
It will also help you save your sanity to develop and test on a desktop
browser first before moving to a mobile device.
286 Chapter 7
www.it-ebooks.info
mobile apps in the real world
3 Add a CACHE: section and list the main pages of the site, as well as the JavaScript
and CSS files.
Refer to the syntax
on page 285.
4 Update the <html> tag on index.php, build.php, tartans.php, and findevent.php with
a manifest attribute.
The manifest.appcache.php file you created should look something like the one below. Note that
we’re also listing the CSS and JavaScript files from jQuery’s content delivery network (CDN).
manifest.appcache.php
The HTML tag on the Tartanator
pages should now look like this.
<html manifest="manifest.appcache.php">
288 Chapter 7
www.it-ebooks.info
mobile apps in the real world
Frustrated Web Dev: Argh. As I navigate around appCache: Well, that’s not exactly true, either.
the Tartanator site, a bunch of images and icons and I gather you’ve learned about the CACHE section,
stuff aren’t showing up, even though I’m online. but haven’t heard anything yet about the NETWORK
appCache: Well, that’s because you neglected to
section.
include some of these resources in the CACHE list. FWD: What’s it for?
appCache: The NETWORK section lets you define
You should go round them up and add them to the
cache manifest.
FWD: So, I need to list every resource on the site or
resources that you don’t want to cache, and for
which the browser should request fresh copies when
they won’t show up at all? a connection is available. It has a special handy‑
appCache: No. You need to add the resources that
dandy wildcard token, *, which means that anything
not explicitly listed in the CACHE section should be
are needed by the HTML files in the cache.
FWD: I’m totally confused. What does it even mean
retrieved from the server.
FWD: Eureka! That sounds like the answer I need
for an HTML file to be in the cache?
appCache: You already know one way to include
here.
appCache: Take caution. If something is in the
an HTML file in the application cache: listing it
NETWORK section, either explicitly or by dint of the
explicitly in the CACHE section of the manifest
* wildcard, it will always be requested afresh. So you
file. But it’s also worth noting that any HTML
need to choose your path carefully.
file that has a manifest attribute on its HTML
tag is included in the cache manifest, even if it’s Decide what things should really be available offline
not explicitly listed there. Only those pages listed and list them in the CACHE section. It sounds like
in the manifest or referencing it in a manifest you do need to track down some icons and images,
attribute—that is, in the cache—need to have all of for example. But for things that really are dynamic—
their resources added to the cache list. login screens, API calls, etc.—let the NETWORK
FWD: OK, so for any page in the cache, if I neglect
wildcard do its work.
to add each and every resource to the CACHE
section, any missed resource won’t ever load, even if
I’m online.
290 Chapter 7
www.it-ebooks.info
mobile apps in the real world
It’s time to make our cache manifest behave a bit better. Let’s integrate
some of the lessons we’ve learned into the manifest.appcache.php file.
NETWORK:
*
CACHE:
http://code.jquery.com/mobile/1.0rc1/jquery.mobile-1.0rc1.min.css
http://code.jquery.com/jquery-1.6.4.min.js
http://code.jquery.com/mobile/1.0rc1/jquery.mobile-1.0rc1.min.js
http://code.jquery.com/mobile/1.0rc1/images/ajax-loader.png
http://code.jquery.com/mobile/1.0rc1/images/icons-18-white.png
http://code.jquery.com/mobile/1.0rc1/images/icons-18-black.png
http://code.jquery.com/mobile/1.0rc1/images/icons-36-white.png
http://code.jquery.com/mobile/1.0rc1/images/icons-36-black.png
index.php
tartans.php
css/styles.css
292 Chapter 7
www.it-ebooks.info
mobile apps in the real world
Frank: I went and read up about this. I admit I got a bit sucked in.
Here’s how it works. Say your browser already has a cache manifest
file for the site. Then say you visit the tartans listing page again later
after new tartans have been created. Your browser will notice that
the cache manifest file has changed—it’s different from the one the
browser already had because the list of tartan files in it has changed.
Your browser will immediately grab the new manifest file and check for
updated or new stuff.
Jim: Then why the heck doesn’t the updated or new stuff show up
right away?
Frank: The browser doesn’t wait around for all of the resources that
are updated or new to download before rendering the page. Once the
browser does finish downloading stuff, the new or updated assets are
ready to go, in the browser’s cache, but won’t show up until the page is
refreshed.
Jim: So, the only way for folks to see updated things is to reload.
Frank: Well, I think I might have a workaround for this particular
situation. I wrote a tiny little JavaScript tool—
Jim: Always with the JavaScript!
Frank: The part of the page that’s dynamic is the stuff that gets output
by the PHP file included in it—that is, list.php. It outputs one <li> per
tartan. The rest of the page is static. We really only care about updating
the contents of the tartan list <ul>.
Jim: True.
Frank: My code uses the window.applicationCache object
and its methods to see if there has been an update to the cache—which
there will be if the manifest file has changed, right? If there has been
an update, we want to get the updated output from list.php.
Jim: Right. If the cache manifest has updated, we know the tartan list
should be updated. Preferably without the user having to reload the
entire page.
Frank: Yeah. So, if there has been an update to the cache manifest, my
code sends an AJAX request to list.php. list.php isn’t in the manifest and,
when requested directly, will always return HTML markup representing
the current list of tartans. I then take the markup returned by list.php and
replace the current—that is, stale—list on the page with it. Voilà!
294 Chapter 7
www.it-ebooks.info
mobile apps in the real world
Test Drive
Let’s take Frank’s little JavaScript library for a spin and see if it helps us wrap up this
complex adventure with appCache.
tartans.php
Q: If you can use a wildcard in the Q: Our manifest contains all of the Q: All of this is well and good, but
NETWORK section of a cache manifest, tartan images and HTML files. Isn’t that what happens if the user’s browser
can’t I just use a wildcard in the CACHE an awful lot to download all in one go? doesn’t support appCache?
section to cache everything on my site
and leave it at that? A: We agonized over that a bit. It is a
fair number of HTTP requests, yes. But
A: The site basically behaves like it did
before we added a cache manifest. It works
A: For better or worse, you can’t use
wildcards in the CACHE section. The
the files are rather minute: most of the
images are under 1 KB and the HTML files
fine, but won’t have a nice offline experience.
special wildcard token is only for the are even smaller. So, the bandwidth hit is
small, and, because the resources are being
Q: You totally didn’t mention the
NETWORK section, and it’s not really a FALLBACK section.
wildcard. You can’t combine it with any other downloaded asynchronously, the impact on
the user should be minimal.
text patterns—it is a standalone thing with a
specific meaning (which is: unless a given
A: In addition to the CACHE and
resource on the site is listed in another Q: Does the browser redownload
NETWORK sections, there is an optional
FALLBACK section that allows you to list
section explicitly, request it over the network everything in the manifest every time it’s
updated? the offline variants that should be used when
when possible).
an online variant is unavailable—for example,
use offline.html instead of login.html.
Q: What is the point of making it so A: Thankfully, no. The browser will check
that pages with a manifest attribute
in their HTML tags get cached even if
to see if the resources it already has cached
have changed but will not download them
Q: appCache is nice, but what about
again unless they’ve been modified. localStorage? It feels like only half of the
they’re not listed in the manifest?
story here.
Q: What’s this about “all in one go”? Watch out for implicit caching
via the manifest attribute.
A: When a browser gets a new or
updated cache manifest file, it immediately We mentioned it already, but we’re
starts downloading all of the new resources going to pound it home: any page
and/or checking for updates to existing ones. that has a manifest attribute
This is something to consider, seriously, on its <html> tag will be cached, whether or
when designing your cache manifests. not it’s listed explicitly in the cache manifest.
And, no, you can’t get around this by using the
NETWORK section or any other trickery.
296 Chapter 7
www.it-ebooks.info
mobile apps in the real world
WiFi networks
Cell towers
GPS
24.21.168.0
Device’s IP address
Where
am I
?
RFID tags
298 Chapter 7
www.it-ebooks.info
mobile apps in the real world
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
message
coords
navigator.geolocation longitude
tion onGeoSuccess
coords posi
"Browser doesn't support geolocation"
position
position
getCurrentPosition()
getCurrentPosition
onGeoError
getLocation latitude coordinates
function getLocation () {
// Verify the browser supports W3C geolocation
if ( ) {
navigator.geolocation. ( , onGeoError);
} else { // It doesn't
onGeoError(new Error( ));
}
}
function onGeoSuccess ( ) {
var = .coords;
alert(coordinates. + ',' + coordinates. );
}
function (error) {
alert(error. );
}
();
300 Chapter 7
www.it-ebooks.info
mobile apps in the real world
2 Add a select input element.The displayed options should show Find us_states.txt in the
the name of the 50 US states. The values should be the two‑letter extras/events directory
postal abbreviations of the states. to help you along.
The submit input button should have an id of search_submit.
3
Don't forget to wrap the
fields in a <div> with a
data-role of fieldcontain
(the jQM way).
function getLocation () {
// Verify the browser supports W3C geolocation
if ( navigator.geolocation ) {
navigator.geolocation. getCurrentPosition ( onGeoSuccess , onGeoError);
} else { // It doesn't
onGeoError(new Error( "Browser doesn't support geolocation" ));
}
}
302 Chapter 7
www.it-ebooks.info
mobile apps in the real world
Geolocation Construction
We’re going to fancy up the code in geolocation.js. Let’s walk through the highlights.
(function () {
var $page, $searchForm, $submitButton, $stateFilter;
$page = $('#event_page');
if (!$page.data.initialized) {
$page.live('pagecreate', initGeo); When the page initializes,
$page.data.initialized = true; call the initGeo function.
}
function initGeo() {
$searchForm = $('#search_form');
$submitButton = $('#search_submit');
$stateFilter = $('#state_filter');
if (navigator.geolocation) { If the browser supports geolocation,
initGeoOptions(); initialize the geolocation-related
} form elements.
}
function initGeoOptions() {
var $latField, $longField, $flipSwitch;
$flipSwitch = $('<select name="usegeo" id="usegeo" Add a slider-themed
data-role="slider"><option value="off">Off</ on/off switch to let
off><option value="on">On</option></select>'). users opt in to using
change(toggleLocation); their current location.
$flipSwitch.prependTo($searchForm).wrap('<div data-
role="fieldcontain"></div>');
$flipSwitch.before('<label for="usegeo">Use my
Location:</label>'); Add two hidden fields
$latField = $('<input type="hidden" />').attr({ name to hold the value of
: 'latitude', id : 'latitude'}) latitude and longitude
$longField = $('<input type="hidden" />').attr({ from the geolocation.
name: 'longitude', id : 'longitude' })
$latField.appendTo($searchForm);
$longField.appendTo($searchForm);
}
304 Chapter 7
www.it-ebooks.info
mobile apps in the real world
toggleLocation is bound
to the change event on
the slider switch.
function toggleLocation(event) {
var geoActivated = ($(event.target).val() If the user just flipped it on,
== 'on') ? true : false; disable the state filter, and
if (geoActivated) { disable the submit button (it
$submitButton.button('disable'); will be reenabled when the
$stateFilter.selectmenu('disable'); geolocation is complete).
$.mobile.showPageLoadingMsg();
navigator.geolocation.getCurrentPosition(
onGeoSuccess, onGeoError);
Here's where we trigger
} else {
the geolocation.
$stateFilter.selectmenu('enable'); When it's turned off, reenable
$submitButton.button('enable'); filter by state.
}
}
function onGeoSuccess(position) { Here's our success callback.
var coordinates = position.coords; We'v e altered it to update
$('#latitude').val(coordinates.latitude); the latit ude and longitude
$('#longitude').val(coordinates.longitude); hidd en fiel ds with the
$.mobile.hidePageLoadingMsg(); user 's loca tion data.
$submitButton.button('enable');
}
On error, slide the use
geolocation switch back to
function onGeoError(error) {
the off position and fire its
$('#usegeo').val('off').trigger('change');
change event (which is bound
alert(error.message);
to toggleLocation above).
}
})();
Try it out! Play with the form You can find this code in the
to get a feel for what the new chapter7 folder in extras/js/
JavaScript does for us. enhanced_geo_form.js.
Update the geolocation.js file, save it, and try
out the updated Find Events page.
Jim: I was just checking out the geolocation piece on some devices. I know that
the BlackBerry OS 5 browser is supposed to have geolocation, but the Use My
Location switch isn’t showing up.
Frank: Yeah. The BlackBerry OS 5 browser supports geolocation, but it isn’t the
W3C flavor. I was just looking this up. And older Android browsers don’t have
W3C‑style geolocation, either. They’re based on Google Gears.
Jim: This sounds complicated.
Frank: It is. And we’re on a tight deadline. I don’t think we have time to chase
down all of the odds and ends and do exhaustive testing on a whole bunch of
obscure devices. What I did find is this open source, drop‑in JavaScript library that
handles geolocation across a bunch of different platforms, W3C‑compliant or no.
It’s called, simply enough, geo-location-javascript.
Jim: But doesn’t that mean we’d have to go refactor all of our existing JavaScript?
Frank: Nope. The API for this library emulates that of the W3C spec. All of the
major method and attribute names are the same. I think we only need to change
a few lines and then we can stop worrying quite so much about cross‑platform
compatibility.
Jim: Oh, while we’re making edits to the JavaScript…the pop‑up error for
geolocation failures is ugly. And could use some finesse in wording.
Frank: Yep. I think we should use a jQuery Mobile dialog, like the ones I built for
form errors on the tartan‑creation form.
Jim: Oh, you didn’t tell me about that!
Frank: If you try to submit the tartan form without a title, or if you forget a color
or size when you add a color‑size combo, a dialog will pop up to alert you to the
errors of your ways. It’s styled in a nice, jQM way.
Jim: How do you make a jQuery Mobile dialog?
Frank: They’re standalone jQM pages. Check out the ones in the dialogs directory.
Then I make them show up from the JavaScript.
Do this!
Jim: Oh, cool. I can probably figure this out.
306 Chapter 7
www.it-ebooks.info
mobile apps in the real world
Update the Find Events page and the geolocation JavaScript to use the cross‑platform
geolocation code and show geolocation errors in a pop‑up dialog.
<div data-role="content">
<script src="http://code.google.com/apis/gears/gears_init.js" type="text/
javascript" charset="utf-8"></script>
<script src="js/geo.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="js/geolocation.js"></script>
if (navigator.geolocation) {
initGeoOptions();
}
to:
if (geo_position_js.init()) {
initGeoOptions();
}
navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);
to:
geo_position_js.getCurrentPosition(onGeoSuccess, onGeoError);
Here’s what your onGeoError function should look like after you convert the
error from a basic JavaScript alert to a jQuery Mobile dialog. We trust you also
made the HTML page for the dialog itself!
function onGeoError(error) {
$('#usegeo').val('off').trigger('change');
$.mobile.changePage( "dialogs/geolocation_error.html", {
transition: "pop",
reverse: false,
role: 'dialog'
});
}
Test Drive
Enough, already! Let’s see this thing in action. It won’t take much to hook this thing up
to some search code and sample data.
2 Try it out!
Head to the Find Events page in your mobile browser of choice and hit the
Use My Location switch.
308 Chapter 7
www.it-ebooks.info
mobile apps in the real world
Nothing found
Ha, ha. Sorry about that. Unless you’re lucky enough to be in
the Portland, Oregon, metro area, you probably got this result
on your first location‑based search:
d,
Unless you’re near Portlanyour
you'll get th is re sul t on
first try.
That’s because all of the sample data is local, and the search
radius is set to 25 miles. How’s about you add some of your
own fake events to get this thing to deliver some results?
Add a few events in the sample data that are in your neck of the woods. Find the event_list.inc file
in chapter7/inc/. Inside is a big PHP array representing fake data for events. Add a few of your own
elements to this array, using an address and lat/long pairs that are within 25 miles of you.
If you feel particularly uncomfortable with PHP, you could try just updating the address and
lat/long of a few existing entries. The latitude, longitude, and state are what is used by the
search script to find matches.
Use this tool to get a lat/long
pair real quick for any address:
http://itouchmap.com/latlong.html.
310 Chapter 7
www.it-ebooks.info
mobile apps in the real world
Web apps that feel natural and comfortable on mobile In our cache manifest file, we can indicate which
devices often share certain characteristics like well- resources should be downloaded and cached for offline
considered progressive enhancement, a good use (in the CACHE section) as well as those that
offline mode, and location-aware features. should be requested afresh when an Internet connection
is available (in the NETWORK section).
Starting with a baseline is a great way to reach as
many users as possible, and thoughtful progressive Geolocation in the browser is supported widely
enhancement for more powerful mobile browsers can among modern smartphones. Many implement
make things really shine. the W3C’s Geolocation API, which exposes the
navigator.geolocation object to JavaScript.
Crafting a relevant offline experience is important:
mobile devices can’t be expected to have an Similarly to how we enhanced the tartan‑creation form
always‑available data connection. for supporting browsers, we also enhanced the Find
Events form to integrate geolocation, when it’s available.
We can take advantage of the appCache feature in
browsers by creating a cache manifest file to instruct Certain mobile browsers, especially on slightly older
the browser which resources to cache and make smartphones, have implementations of geolocation
available offline. that are not W3C-compliant. To manage these
idiosyncracies, we used a third‑party geolocation library
The construction of cache manifests is straightforward
called geo‑location‑javascript.
on the surface, but there are a number of gotchas that
you have to carefully consider. The geo-location-javascript library emulates the
W3C API, requiring minimal changes to our original,
W3C‑specific JavaScript code.
314 Chapter 8
www.it-ebooks.info
build hybrid mobile apps with PhoneGap
Sounds like a
perfect addition
to the Tartanator!
capabilities, like Joe: There are several frameworks and platforms that provide
bridges between web apps and native code. They take our web
the camera, are app, chew on it a bit, and then spit out packaged apps—native
ones—for various platforms. They take care of the various bits
not accessible from and bobs for us so we can just use the web standards we know.
mobile browsers.
Jim: Should we convert the Tartanator to one of these hybrid
apps, then?
Joe: I don’t think we have the time to wrap the entire app
This is slowly changing for the
natively and test it effectively. Given the timeline, what do you
better, but there are still a
think about suggesting that we create a native app just for the
number of things we can’t get at
contest?
from the browser. Frank: I kind of like that idea. And we don’t have to risk
making hurried changes to the Tartanator web app. It has a bit
of cachet—attendees show up and can download a special app
just for the event and the contest. Joe, if you think we can get
the hybrid app thing to work on several platforms, let’s float the
idea with Ewan.
316 Chapter 8
www.it-ebooks.info
build hybrid mobile apps with PhoneGap
318 Chapter 8
www.it-ebooks.info
build hybrid mobile apps with PhoneGap
JavaScript ahead.
You don’t have to be a JavaScript genius
to make it through this chapter, but there’s
no getting around the fact that today’s
web app development involves JavaScript.
To communicate with native functionality such as the
camera APIs using PhoneGap, we need to use a
client-side technology—and JavaScript is obviously
the right guy for this job.
Q: What other tools, products, or services are there for Q: Why did I have to install the Android SDK?
building hybrid apps?
If you have a device that is not Android but is one of PhoneGap Build’s supported
platforms, or if you have an Apple Developer Account, we encourage you to try
building and testing the examples in this chapter on your platform.
Our test kitchen has run the Tartan Hunt app successfully on various flavors of
Android and iOS.
320 Chapter 8
www.it-ebooks.info
build hybrid mobile apps with PhoneGap
Do this!
Get on over to
https://build.phonegap.com and
create an account. It’s free and only
takes a moment.
Landing screen
Tartan and vendor
detail screen
tap
322 Chapter 8
www.it-ebooks.info
build hybrid mobile apps with PhoneGap
324 Chapter 8
www.it-ebooks.info
build hybrid mobile apps with PhoneGap
Let’s make our first PhoneGap Build app. First, we need a configuration file.
Create a file called config.xml in the chapter8 directory. Use the template
below to complete the file’s contents.
Remember that a PhoneGap Build project is either built from a zip file or
pulled from a code repository. We’re going to take the zip file route.
Zip up the entire contents of the chapter8 directory. It doesn’t matter what
the resulting file is called, as long as it is a zip archive with a .zip extension.
Your config.xml file should look something like this. But don’t lose your identity! We expect you to
use your own name and stuff.
config.xml
326 Chapter 8
www.it-ebooks.info
build hybrid mobile apps with PhoneGap
Download the
Android APK.
APK (Android
Application Package
File) is the packaged
app, ready to install.
328 Chapter 8
www.it-ebooks.info
build hybrid mobile apps with PhoneGap
We recommend using an
AVD for Android 2.3 or You should now be able to see the
4.0+. Earlier versions have Tartan Hunt app in the application
somewhat finicky emulators, screen of your device or emulator.
especially for the camera Go ahead and launch the app! it
stuff we’ll do later. The first time you run the appto,
might take a litt le wh ile— up
about 30 seconds—to launch.
you are here 4 329
www.it-ebooks.info
tartan hunting in the wild
330 Chapter 8
www.it-ebooks.info
build hybrid mobile apps with PhoneGap
We could rectify
the iOS situation by What’s with the frowny face for BlackBerry? Well, sadly, there’s a problem
providing a signing currently with the combination of PhoneGap Build, BlackBerry, and any
key (if we had one). filename with a hyphen in it. Several of the jQuery Mobile files we need
have hyphens in their filenames.
For purposes of
brevity and sanity—
and because Ewan has To make the PhoneGap Build Tartan Hunt app work on
expressed diffidence BlackBerry OS, you would need to alter jQuery Mobile’s
about supporting the icon filenames and update any reference to them in jQM’s
BlackBerry platform, source code. While this wouldn’t take too long, it does
we're not going to mean “hacking” jQuery Mobile’s core and introduces a
address this here… maintenance burden. What do you think? Is it worth it?
Let’s add a splash screen so that users don’t have to look at a boring blank
screen while the app loads. Use the PhoneGap Build config.xml documentation at
https://build.phonegap.com/docs/config-xml to figure out how to do this. Find the two splash‑
screen images in chapter8/extras/images and move them to the chapter8/images folder.
Update config.xml, zip up chapter8 again, rebuild the app on PhoneGap Build, and
reinstall it to see the new splash screen take effect.
You need to uninstall the app before you can reinstall it after
making changes.
Each time you rebuild the app on PhoneGap Build and need to reinstall it
on a device or emulator, you need to uninstall first. Run this command when
the device is attached via USB, or when the emulator you want to uninstall it
from is running.
332 Chapter 8
www.it-ebooks.info
build hybrid mobile apps with PhoneGap
config.xml
334 Chapter 8
www.it-ebooks.info
build hybrid mobile apps with PhoneGap
Then, later, we can ask for that value by using its key: The key for which we’d like the
stored data, please!
var storedValue = localStorage.getItem(key);
In our case, when a user found, say, the Douglas tartan at a vendor’s
booth and indicated this by tapping the “I found it!” button, we could do
something like:
localStorage.setItem('douglas', 'true');
336 Chapter 8
www.it-ebooks.info
build hybrid mobile apps with PhoneGap
(function() {
$(document).bind("mobileinit", function() {
$.mobile.page.prototype.options.addBackBtn = true;
});
if (typeof(window.localStorage) == 'object') {
$('.foundTartan').click(tartanFound);
addResetButton();
}
};
$(document).ready(initDevice);
localStorage.setItem(tartanKey, 'true');
};
$resetButton.click(function() {
localStorage.clear();
});
$resetButton.appendTo($('#booths'));
app.js
};
})();
(function() {
$(document).bind("mobileinit", function() { We're turning off the
// Turn off jQM page transitions page transitions because
$.extend($.mobile, { defaultPageTransition: 'none' });
they are slow on some
// Add a back button to the nested list subpages
Android devices.
338 Chapter 8
www.it-ebooks.info
build hybrid mobile apps with PhoneGap
Client‑side feature detection can be quite simple, like this example, but there are
also JavaScript libraries that provide detection for all sorts of features. Modernizr
(http://modernizr.com) is a widely used example of such a tool. We also did feature detection
in Chapter 5 using WURFL
device capability data. That’s
But wait…the story isn’t over yet server-side feature detection.
The leftover comment magnets give us a clue about what else we need to do
here. We’re storing found tartans, and providing a way to clear them all out, but
the interface doesn’t change. We need to write some code that updates the
display so players can see which tartans they’ve found. Turn the page
to get started.
Our leftover magnets.
We need to take care
of these items!
// Get the entry from localStorage By only adding click handlers and the reset
button if localStorage is supported, we are
// Update the display to in effect setting a minimal bar for supported
// show which tartans browsers, Chapter 4 style. Can you think of
// have been found why this might be OK? Can you also think
why it might not be in some cases?
This is jQuery code. It means: iterate (loop) over each element that
So, for each ul.details in matches the CSS selector ul.details (<ul>s with a class of “details”).
the document…
$(document).ready(initDevice);
1 Figure out the name of refreshTartans = function() { app.js
the key to look for in $('ul.details').each(function() {
localStorage by getting the
var myID = $(this).attr('id');
id attribute of this <ul>
and prepending ‘found-' var tartanKey = 'found-' + myID;
var foundValue = localStorage.getItem(tartanKey);
e.g,. ‘found-douglas' var isFound = Boolean (foundValue);
2 Check for that key in $('#vendor-'+ myID).toggleClass('found', isFound);
localStorage. $('[data-url*="'+myID+'"]').toggleClass('found',isFound);
$('#'+tartanKey).closest('li').toggle(!isFound);
3 Toggle the visibility and
classes on some elements to });
reflect whether they’ve $('ul').each(function() {
been found or not. if ($(this).data('listview')) {
$(this).listview('refresh');
4 Refresh the jQuery Mobile }
listviews in the document. });
};
tartanFound = function (event) {
If we don’t, any
altered content won’t
be styled correctly. What’s all that
toggle stuff?
Remember, jQuery Mobile
builds on top of jQuery, toggle and toggleClass
so we have all of jQuery’s are part of jQuery. Let’s
methods available to us. take a closer look.
340 Chapter 8
www.it-ebooks.info
build hybrid mobile apps with PhoneGap
toggleClass will add the CSS class indicated (found) to the elements that
match the selector given if the isFound value is true (and remove the class if
it is false).
Summary: Add the found class
Similarly, toggle will show the <li> element indicated if it’s passed a to two elements and hide the
Boolean with a true value. We’re doing something a bit clever here and giving <li> containing the “I found it!"
it the opposite of the current value of isFound (that’s what !isFound does). button if the tartan has been
Why, you might ask? Well, we want to hide that <li> if the tartan’s been found found. Remove the class and
(that is, isFound is true). That’s the <li> that contains the “I found it!” show the button if not.
button. We don’t need it to show up anymore if the tartan has been found.
app.js
Test Drive
Edit app.js to integrate the changes from the last several pages. Save
the file and preview Tartan Hunt’s index.html in a desktop web browser
(this should work just fine). Try clicking on some tartans and their “I Do this!
found it!” buttons. You should see found tartans and their detail pages
receive some CSS style changes (things will turn green).
If you’re having trouble, use the Web Inspector tool in Chrome or
Safari, or the Error Console in Firefox, to review possible JavaScript Go ahead and zip up the
errors. If you’re really stuck, you can find a finished version of the file in contents of the chapter8
chapter8/extras/scripts/app.localStorage.js. directory again and rebuild on
PhoneGap Build. Install again
You’ll need to replace your on a device or emulator and
app.js with this file if you try it out!
want to use it.
342 Chapter 8
www.it-ebooks.info
build hybrid mobile apps with PhoneGap
Q: Which browsers currently support Q: You said that you can only store strings in
localStorage? localStorage. But earlier you mentioned that you
can use localStorage to store images. How could
A: The short answer is: most of them. But not
Opera Mini. And if you’re still using Internet Explorer
that possibly work?
version 7, you’re out of luck there. A: Strings, yes. But what’s to stop us from storing
rather large strings? Images can be stored as their
Q: Do the keys have to have certain names? BASE64‑encoded strings and used directly as the value
of <img> src attributes or as url() values in CSS
A: Both keys and the values you assign to them
have to be strings. Beyond that, the sky’s the limit. You
background images. Browser support for data‑URIs
(that’s what this is called) is pretty decent, with the big
exception of Internet Explorer. Read more about it in this
can call them whatever pleases you.
article by Nicholas Zakas: http://bit.ly/sWe7HS.
Q: How much data can I store? Q: Wait a minute! I was just looking at the code
again and noticed we're adding a back button on
A: The W3C localStorage Specification is sort
of adorably vague about this. To quote: “A mostly
the nested list pages. That doesn’t make sense for
Androids—most Android devices have hardware
arbitrary limit of five megabytes per origin is back buttons already.
recommended. Implementation feedback is welcome
and will be used to update this suggestion in the
future.”
A: Well spotted. The back button doesn’t just feel
awkward for Android, it actually closes the PhoneGap
Most browsers provide between 2 and 5 MB. Some Build–generated app! That is not good. We’ll come
browsers, like Safari, prompt users to allocate more back to this in just a bit and fix it.
space if the allotment is used up.