HTML5 Mobile Development Cookbook


HTML5 Mobile Development Cookbook Over 60 recipes for building fast, responsive HTML5 mobile websites for iPhone 5, Android, Windows Phone, and Blackberry Shi Chuan BIRMINGHAM - MUMBAI HTML5 Mobile Development Cookbook Copyright © 2012 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: February, 2012 Production Reference: 1240112 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-84969-196-3 www.packtpub.com Cover Image by Rakesh Shejwal (shejwal.rakesh@gmail.com) Credits Author Shi Chuan Reviewers Dale Cruse Sarah Soward Shawn McBurnie Acquisition Editor Alina Lewis Lead Technical Editor Shreerang Deshpande Technical Editor Sakina Kaydawala Project Coordinator Leena Purkait Proofreader Bernadette Watkins Indexer Monica Ajmera Mehta Production Coordinator Prachali Bhiwandkar Cover Work Prachali Bhiwandkar About the Author Shi Chuan has over five years experience in web development. He is a member of the HTML5 Boilerplate project, lead developer of Mobile Boilerplate (http://h5bp.com/ mobile), owner of the JavaScript Patterns project (http://shichuan.github.com/ javascript-patterns). He is now an independent developer living in the UK and China. You can find out more about him on his personal website at: http://www.blog.highub. com. He loves reading, travelling, great food, and eclectic and indie music. I would like to thank my parents, and the whole family who have been my positive and unconditional supporters. I would also like to thank Jiang Xue, who taught me so many things about life, in ways she does not even know. I would also like to thank my friends from the Boilerplate Team - Paul Irish, Divya Manian, Mathias Bynens, and Nicolas Gallagher. Former CTO of the company I worked for - Chi Tran. They have been and will always be my inspiration and aspiration. About the Reviewers Dale Cruse, a Boston-area web developer, is the author of HTML5 Multimedia Development Cookbook. He has been publishing websites for high-profile clients ranging from the U.S. Army to Bloomingdale's since 1995. He has been a guest lecturer at the Art Institute of New England and is currently pursuing speaking opportunities. Contact him at http://dalejcruse.com. He is also the author of the Champagne blog Drinks Are On Me at http://drinksareonme.net. Sarah Soward teaches coding, design, and the Adobe Creative suite at the Bay Area Video Coalition and AcademyX. In addition to teaching, she also developed the curriculum for BAVC's HTML5/CSS3, Color Theory, Typography, Fireworks, and Web Design Workflow classes. For a number of years, she was the Art Director of non-profits. She is the co-author of the WordPress and Flash Cookbook. When she isn't teaching, she's designing and developing everything from business cards to websites, painting rhinos, building stuff, and banging on a drum till her hands keep their own beat. She likes to keep busy. www.PacktPub.com Support files, eBooks, discount offers and more You might want to visit www.PacktPub.com for support files and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.  Why Subscribe? ff Fully searchable across every book published by Packt ff Copy and paste, print and bookmark content ff On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access. For Claire Jiang Xue Table of Contents Preface 1 Chapter 1: HTML5 and the Mobile Web 5 Introduction 5 Setting up mobile development tools 9 BlackBerry simulator 11 Setting up the mobile development environment 13 Using HTML5 on the mobile web 18 Rendering HTML5 across different browsers 20 Designing for mobile 23 Defining a content strategy 31 Chapter 2: Mobile Setup and Optimization 35 Introduction 35 Adding a home screen button icon 36 Preventing text resize 39 Optimizing viewport width 44 Fixing Mobile Safari screen re-flow scale 48 Launching phone-specific programs from the browser 52 Enabling iPhone start screen in full screen mode 56 Prevent iOS from zooming onfocus 58 Disabling or limiting WebKit features 59 Chapter 3: Interactive Media with Mobile Events 63 Introduction 63 Moving an element with touch events 63 Detecting and handling orientation event 66 Rotating an HTML element with gesture events 74 Making a carousel with swipe events 77 Zooming an image with gesture events 82 ii Table of Contents Chapter 4: Building Fast and Responsive Websites 85 Introduction 85 Building pages using HTML5 semantics 86 Using CSS3 features for progressive enhancement 89 Applying responsive design 94 Optimizing polyfills script loading 97 Applying user agent detection 100 Adding mobile bookmark bubble to the home page 102 Building Contact page with textarea and autogrow forms 104 Making buttons with instant response 106 Hiding WebKit chrome 109 Building a mobile sitemap 112 Chapter 5: Mobile Device Access 115 Introduction 115 Getting your location 116 Handling cross-browser geolocation 119 Displaying a map based on your geolocation 121 Displaying location in realtime 126 Using the DeviceOrientation event 130 Using geolocation with foursquare 134 Chapter 6: Mobile Rich Media 137 Introduction 137 Playing audio on mobile 138 Streaming video on your mobile 142 Using offline caching 145 Using Web Storage on mobile 148 Using web workers 152 Creating Flash-like navigation with session and history API 157 Chapter 7: Mobile Debugging 163 Introduction 163 Remote debugging with Opera Dragonfly 163 Remote debugging with weinre 167 Using Firebug on mobile 171 Remote JavaScript debugging with JS Console 174 Setting up Mobile Safari debugging 179 Chapter 8: Server-Side Tuning 187 Introduction 187 Preventing mobile transcoding 188 Adding mobile MIME types 189 iii Table of Contents Making cache manifest display properly 191 Setting far future expire headers 191 Compressing files using Gzip 194 Removing ETags 197 Chapter 9: Mobile Performance Testing 201 Introduction 201 Speed testing your device with Blaze 202 Analyzing mobile page speed online 205 Analyzing mobile performance with PCAP Web Performance Analyzer 207 Using HTTP Archive Mobile 209 Storing performance data with Jdrop 211 Chapter 10: Emerging Mobile Web Features 215 Introduction 215 window.onerror 216 Using ECMAScript 5 methods 217 New HTML5 input types 222 Inline SVG in text/HTML 224 position:fixed 225 overflow:scroll 226 Index 229 Preface How do I create fast and responsive mobile websites that work across a range of platforms? For developers dealing with the proliferation of mobile devices each with unique screen sizes and performance limitations, it is an important question. This cookbook provides the answer. You will learn how to apply the latest HTML5 mobile web features effectively across a range of mobile devices. HTML5 Mobile Development Cookbook will show you how to plan, build, debug, and optimize mobile websites. Apply the latest HTML5 features that are best for mobile, while discovering emerging mobile web features to integrate in your mobile sites. Build a rock-solid default mobile HTML template and understand mobile user interaction. Make your site fast and responsive, leveraging the uniqueness of location-based mobile features and mobile rich media. Make your mobile website perfect using debugging, performance optimization, and server-side tuning. The book finishes with a sneak preview of future mobile web technologies. What this book covers Chapter 1, HTML5 and the Mobile Web, introduces HTML5 and the mobile web, along with some emulators and simulators. Chapter 2, Mobile Setup and Optimization, discusses various mobile setups and optimization, such as preventing text resize and optimizing viewport width. Chapter 3, Interactive Media with Mobile Events, discusses mobile interactions such as gesture events. Chapter 4, Building Fast and Responsive Websites, talks about the various ways to make mobile websites fast and responsive. Chapter 5, Mobile Device Access, discusses location-based mobile web and other HTML5 device-specific features. Preface 2 Chapter 6, Mobile Rich Media, talks about the HTML5 rich media elements that can be used on mobile browsers. Chapter 7, Mobile Debugging, teaches you ways to work around mobile screen-side constraints and debug mobile websites and web apps effectively. Chapter 8, Server-Side Tuning, focuses on the server-side tuning for mobile websites. Chapter 9, Mobile Performance Testing, teaches you various Tools and techniques that can be used to boost mobile performance. Chapter 10, Emerging Mobile Web Features, talks about ECMAScript 5 as well as mobile-specific features that were added to allow more functionalities with mobile and boost the performance. What you need for this book A text editor is all that is needed for most recipes in the book. You should also have a mobile device such as an iPhone, Android, Blackberry, or other device suitable for testing. Although it is best to test things out on a real device, don't worry if you don't have one, because we will cover details on how to use emulators and simulators to test, in case a real device is not available. Who this book is for Developers keen to create HTML5 mobile websites that are fast and responsive across a whole range of mobile devices. Conventions In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text are shown as follows: "geolocation is a new property on the navigator object." A block of code is set as follows: var latitude = position.coords.latitude; var longitude = position.coords.longitude; var accuracy = position.coords.accuracy; Preface 3 When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: var latitude = position.coords.latitude; var longitude = position.coords.longitude; var accuracy = position.coords.accuracy; New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Click on the Start button in the Capture Options dialog to start capturing." Warnings or important notes appear in a box like this. Tips and tricks appear like this. Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply send an e-mail to feedback@packtpub.com, and mention the book title via the subject of your message. If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail suggest@packtpub.com. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors. Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase. Preface 4 Downloading the example code for this book You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you. Errata Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support. Piracy Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at copyright@packtpub.com with a link to the suspected pirated material. We appreciate your help in protecting our authors, and our ability to bring you valuable content. Questions You can contact us at questions@packtpub.com if you are having a problem with any aspect of the book, and we will do our best to address it. 1 HTML5 and the Mobile Web In this chapter, we will cover: ff Getting your mobile device ready ff Emulators and simulators ff Setting up the mobile development environment ff Using HTML5 on mobile web ff Making HTML5 render cross browser ff Designing for mobile ff Determining your target mobile devices ff Defining a content adaptation strategy Introduction Both HTML5 and mobile web are promising technologies. Both have relatively short histories. In this chapter, most topics we will be covering are relatively basic. This is to help you get started with mobile development quickly and with minimum effort. Both mobile and HTML5 are still evolving in nature and there could be many questions in your mind. We will clear those doubts and set your mind focused on things that matter. HTML5 and the Mobile Web 6 The mobile web is growing fast. We now have mobile Safari which is one of the most used apps on the iPhone, allowing developers to build high performance web applications and enhancing users' browsing experience. You do not need a developer account to host and run a mobile site, you don't need to get approval from any app market to launch a mobile website and you can make updates any time you like without the hassle of waiting for approval. All these are benefits of mobile web development, but at the same time, there are challenges such as inconsistencies among browsers, the lack of certain features compared to native apps, and security. We can't tackle them all, but we sure can solve some of them. And we will see, when developing a mobile site, how we can separate the common practices from the best practices. There are literally thousands of smartphones out there; you don't need every single one of them to test your application on. In fact, you may need fewer than 10. If that's still out of your budget, then two devices are good enough. For the rest, you can use simulators/emulators to do the job. This book focuses on six A-grade mobile devices, with focus specifically on iPhone, Android, and Windows Phone: ff iOS ff Android ff Windows Mobile ff Blackberry v6.0 and above ff Symbian 60 ff Palm webOS There are two browsers that are device-independent that will also be covered in this book. They are: ff Opera Mobile ff Firefox Mobile Just because other browsers are not in the list does not mean they won't be covered by the issues and techniques we discuss in this book. Identifying your target mobile devices Target browser: all You can't possibly make a mobile site for every single mobile device. No one has the time or energy to do so. Cross-browser mobile web development can be crazy. It's hard to define the scope of the work, as John Resig (creator of jQuery Mobile) pointed out in his presentation slide describing his experience building jQuery Mobile (http://www.slideshare.net/ jeresig/testing-mobile-javascript), he asked three questions: Chapter 1 7 ff Which platforms and browsers are popular? ff Which browsers are capable of supporting modern scripting? ff What devices and simulators do I acquire to test with? When you are building a mobile site, you have to ask yourself similar questions, but not the exact same questions, because remember your site should be specifically tailored to your target audience. So your questions should be: ff Which platforms and browsers are most commonly used by visitors on my website? ff How many people access my website from a mobile device that is capable of supporting modern scripting? ff Which devices and simulators do I need for testing? Which platforms and browsers are most commonly used by visitors on my website? Now let's answer the first question. Before building a mobile website, you must first find out who are your target audience, and what mobile devices they use when visiting your site. There are many analytics tools that can help you answer these questions. One of those is Google Analytics. You can sign up for a free Google Analytics account at: http://www.google. com/analytics/ The way to do it is fairly straightforward: most developers are no strangers to Google Analytics. All you have to do is to include the JavaScript snippet from the the Google Analytics site and embed it in your web pages. JavaScript can be rendered in most modern smartphones, so there is really no difference between using it on a desktop site and on a mobile site. How many people access my website from a mobile device that is capable of supporting modern scripting? Now let's answer the second question. One thing you may want to find out is the number of people using mobile browsers to surf your site. And you also want to find out how many people use a relic mobile browser that doesn't support JavaScript at all. This is because if the percentage of people using low-end smartphones is higher than that of people using high-end smartphones, it may not be worthwhile using HTML5 in the first place (although the chance of this is very low). So if your goal is not just to know the number of people using smartphones, but also the number of people who use older versions of mobile phones, Google Analytics for mobile comes to the rescue. You can download the script from: http://code.google.com/mobile/analytics/download.html#Download_the_ Google_Analytics_server_side_package HTML5 and the Mobile Web 8 Google Analytics for mobile server-side packages currently supports JSP, ASPX, Perl, and PHP. Let's take a look at one of the examples in PHP. All you have to do is to change the ACCOUNT ID GOES HERE with your GA account ID. But remember to replace 'UA-xx' with 'MO-xx'. Unfortunately, when you use the server-side version, you can't use it on pages where you also use the standard JavaScript tracking code, ga.js. Using the server-side version means that you have to give up the JavaScript version. It can be annoying because the JavaScript version provides a lot of dynamic tracking mechanisms that are lacking in the server-side version: Chapter 1 9 Alternatives to Google Analytics Google Analytics is not the only mobile analytics service in the market. There are other services providing more specialized services. For example, PercentMobile is a hosted mobile analytics service that makes your mobile audience and opportunities clear. You can find out more about this service at: http://percentmobile.com/ Accuracy of Google Analytics The location reported by mobile devices may not always be accurate; Google Analytics uses IP addresses to determine user location for Map Overlay reports. They are subject to possible inaccuracy, as mobile IPs originate from the wireless carrier gateway which is not necessarily co-located with mobile users. Server loading speed concern Due to the server-side processing, some additional server load may be incurred. Google recommends you first test the snippet on a few of your pages to ensure all is well before rolling out to an entire site. Setting up mobile development tools Target browser: all Now one question still remains unanswered from the previous recipe: which devices and simulators do I need for testing? We will find this out in this chapter. If you have figured out what major mobile devices you are going to support, now is the time to see how to set them up. Mobile development can be costly if you test on various mobile devices. Although we have all these mobile simulators and emulators available for testing, it's not as good as testing on a real device. Now let's see how we can maximize the testing coverage and minimize the cost. Getting ready We are going to make some assumptions here. Each case is different, but the idea is the same. Let's assume you have a Windows operating system on your desktop, but the top visitors to your site surf using iOS, Android, and Blackberry. HTML5 and the Mobile Web 10 How to do it... Your goal is to maximize the coverage and minimize the cost. All three devices have emulators, but not all support different platforms. Name Compatibility iOS simulator Mac Android emulator Windows, Mac, Linux Blackberry simulator Windows As you can see, since iOS simulator only works for Mac, and if you are running a Windows OS, the best and only choice is to purchase an iPhone for testing. For Android and Blackberry, because they both have emulators for Windows, to save budget, you can download the emulators. How it works... 1. List the top mobile devices people use to surf your site. 2. Know the machine OS you are using for the development. 3. Find out the compatibility of each of these device emulators to your development environment. There's more... If you have the budget for more than one mobile device having a different OS, you can think further about screen sizes and the DPI of the mobile device. You may not need to buy two high-end devices. For instance, it's not necessary to own an iPhone4 and an Android Thunderbolt. You can buy a lower-end of Android just to test out how your site would look on a lower-end device. So the idea is to combine your OS, mobile devices, and emulators to maximize the scenarios to cover. Device simulator/emulator download lookup table The following table shows a list of popular mobile device emulators for mobile web design and development testing: Name Type Compatibility URL iOS Simulator Mac https://developer.apple. com/devcenter/ios/index. action#downloads Android Emulator Mac, Win, Linux http://developer.android.com/ sdk/index.html Chapter 1 11 Name Type Compatibility URL HP webOS Virtual Machine Mac, Win, Linux http://developer.palm.com/ index.php?option=com_content&v iew=article&id=1788&Itemid=55 Nokia Symbian Emulator Win http://www.forum.nokia.com/ info/sw.nokia.com/id/ec866fab- 4b76-49f6-b5a5-af0631419e9c/ S60_All_in_One_SDKs.html Blackberry Emulator Win http://us.blackberry.com/ developers/resources/ simulators.jsp Windows Mobile 7 Emulator Win http://www.microsoft.com/ downloads/en/details. aspx?FamilyID=04704acf-a63a- 4f97-952c-8b51b34b00ce Browser simulator/emulator download lookup table Apart from device testing tools, we also have tools for platform-independent browsers, notably Opera and Firefox. These are shown in the table below: Name Type Compatibility URL Opera Mobile Emulator Mac, Win, Linux http://www.opera.com/ developer/tools/ Opera Mini Simulator Mac, Win, Linux http://www.opera.com/ developer/tools/http:// www.opera.com/mobile/demo/ Firefox for Mobile Simulator Mac, Win, Linux http://www.mozilla.com/en- US/mobile/download/ Remote testing Apart from emulators and simulators, there are also test frameworks that give you remote access to REAL devices. One of those tools is DeviceAnywhere; one problem is that it is not free. http://www.deviceanywhere.com/ BlackBerry simulator Target Browser: BlackBerry Most mobile device simulators are easy to install and configure if you follow the instructions on their sites, but BlackBerry simulators work differently from other mobile device simulators. For Blackberry device simulators, to connect to Internet, besides downloading the simulators, you also need to download and install BlackBerry Email and MDS Services Simulator. HTML5 and the Mobile Web 12 Getting ready Make sure you have chosen a simulator to download from: http://us.blackberry.com/ developers/resources/simulators.jsp How to do it... First, go to the page: https://swdownloads.blackberry.com/Downloads/ entry.do?code=A8BAA56554F96369AB93E4F3BB068C22&CPID=OTC- SOFTWAREDOWNLOADS&cp=OTC-SOFTWAREDOWNLOADS. There you will see a list of products similar to the following screenshot: Now select BlackBerry Email and MDS Services Simulator Package and then click on Next. After downloading and installing the software, you must first launch the service simulator before the Blackberry simulator, in order to allow it to connect to the Internet. Chapter 1 13 The following is a screenshot of a Blackberry simulator: Setting up the mobile development environment Target browser: all Before we start mobile web development, we have to first set up a development environment. HTML5 and the Mobile Web 14 Getting ready 1. Se t up localhost on your machine. For Windows, Mac, or Linux, the easiest way to set it up is to use the popular and free XAMPP software: (http://www.apachefriends.org/en/index.html). 2. Make sure you have a wireless connection. 3. Also you should have a mobile device with you. Otherwise, use a mobile simulator/emulator. 4. Ensure your mobile device and your desktop are on the same wireless network. How to do it... 1. Creat e an HTML file and name it ch01e1.html at the root directory of your localhost: Inside ch01r01.html, type in the following:
Main Navigation here
body content here
Footer links here
2. No w get your IP address. If you are using Windows, you can type the following line in your command prompt: ipconfig Downloading the example code for this book You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub. com/support and register to have the files e-mailed directly to you Chapter 1 15 3. Once y ou have got your IP address, (for example, 192.168.1.16.), enter it in your mobile browser URL address bar. Now you should see the page load with the text displayed: How it works... Within the same network, your mobile device can access your desktop host through your desktop IP address. There's more... If you don't have a mobile device, you can use one of the simulators for testing. But it's recommended to have at least one or two real mobile devices for testing. A simulator could test most things, but not everything, accurately. HTML5 and the Mobile Web 16 Testing on a Safari desktop If your main target audience is iPhone mobile Safari users, you can also do testing on a desktop to save time. To do so, open up Safari, go to Preferences, click on the Advanced tab, check Show Develop menu bar as shown next: Now click on the display menu for the current page, choose Develop | User Agent | Mobile Safari 3.1.3 – iPhone: Chapter 1 17 List of community-based collection of emulators/simulators There is a list of emulators and simulators available if you really don't have a Smartphone at hand. You can find the list on a wiki on the Mobile Boilerplate project: https://github.com/h5bp/mobile-boilerplate/wiki/Mobile-Emulators-&- Simulators List of emulators/simulators collection by Firtman Maximiliano Firtman, a mobile and web developer, also an author, maintains a list of emulators on his site at: http://www.mobilexweb.com/emulators HTML5 and the Mobile Web 18 Using HTML5 on the mobile web Target browser: all Now we are going to create a simple HTML5 page for your mobile device. If you already have experience with older versions of HTML, HTML5 should be easy to understand. And if you have made a web page for desktop before, it won't be hard for you to make one for a mobile device. Getting ready Create a new file ch01e2.html. How to do it... Save the following code in the file: hello to the HTML5 world! Now render this in your mobile browser, and you should see the text render just as expected. How it works... As you can see, the only difference between HTML5 and other HTML pages is the Document Type Definition (DTD) we used: . You might have seen the code and are wondering what it does. It helps Mobile Safari to know that the page is as wide as the device. Setting initial-scale=1 tells the browser not to zoom in or out. Chapter 1 19 There's more... Here's a little bit of history of HTML5: there are two versions of HTML5 draft, one created by W3C and the other by WHATWG. The W3C is run by a group that is democratic in nature, but super slow in practice. WHATWG is edited by one person, Ian Hickson (who is also working for Google), and a group of people who are not public. As Ian does most of the decision making, it makes WHATWG's version progress faster. HTML5 and version number You might be wondering why HTML5 is being so ambiguous by using a declaration without even a version number. Well there are many reasons to justify this: 1. Version support of HTML doesn't matter much to browsers. What matters is the feature support. In other words, if the browser supports the HTML5 feature you are using, even if you declare the document as HTML4, it will still render the HTML5 element as expected. 2. It's easier to type! Mobile doctypes One question you may ask is whether it is safe to use the HTML5 DTD . The answer is DTDs were made for validation, not browser rendering. Your next question might be: what about quirks mode? is the minimum information required to ensure that a browser renders in standards mode. So you are pretty safe to use . You may have noticed that we use instead of . The reason is HTML5 is not case sensitive, but for consistency with other HTML tags, we will use lowercase throughout the book. Free resources to learn HTML5 There are many excellent and free books, and articles about basic HTML5 tags. If you are unfamiliar with HTML5, you can check out one of the following: ff HTML5 Doctor: http://html5doctor.com/ ff Dive Into HTML5: http://diveintohtml5.org/ ff HTML5 Rocks: http://www.html5rocks.com/ HTML5 and the Mobile Web 20 If you are the kind of person who really wants to know every detail about something, you can read the official HTML5 specs. The W3C version of the spec is at: http://dev.w3.org/html5/spec/Overview.html The WHATWG version of HTML Living Standard is at: http://www.whatwg.org/specs/web-apps/current-work/multipage/ Rendering HTML5 across different browsers Target browser: all There are older mobile browsers that don't recognize HTML5 elements. The problem with this is that you can't style these elements if they are not recognized. There are many shims made to tackle this issue. One of those is Modernizr. Getting ready 1. One of the mobile browsers that doesn't recognize HTML5 elements is Windows Mobile. If you don't have Windows Mobile, you can simply use IE7 to test this out, because they are based on the same engine. 2. Download Modernizr from the site: http://www.modernizr.com/. It was written by Faruk Ateş, Paul Irish, and Alex Sexton. How to do it... 1. Creat e an HTML file and name it ch01e3.html, and enter the following code in the file:
Main Navigation here
Chapter 1 21 body content here
Footer links here
2. No w create another page with Modernizr included, and name it ch01e4.html:
Main Navigation here
body content here
Footer links here
HTML5 and the Mobile Web 22 How it works... Remember that if you use Modernizr for your project, you should always include it at the head of the file before the end of the tag. There are other polyfills used for similar purposes, and some are listed in the following section. There's more... Modernizr is not the only script library helper out there; there are two other notable ones: ff html5shim by Remy Sharp, Jonathan Neal & community, enabled for print use, as well as at: http://code.google.com/p/html5shim/ ff innerShiv by Joe Bartlett, enables elements for innerHTML use at: http://jdbartlett.github.com/innershiv/ HTML5 CSS reset You may want to reset the set of new CSS HTML5 elements in your stylesheet: article, aside, canvas, details, figcaption, figure,footer, header, hgroup, menu, nav, section, summary,time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } Enable block-level HTML5 elements in older IE In your CSS, you might want to include the set of block-level HTML5 elements in your CSS reset. Do note that not all HTML5 elements have to be displayed as block elements. Here is a list of block-level HTML5 elements: article, aside, details, figcaption, figure,footer, header, hgroup, menu, nav, section { display: block; } Modernizr Modernizr does more than just making HTML5 elements stylable in CSS. It also helps to detect HTML5 feature support in the browser used for rendering. With version 2.0, you will have the option to customize the download http://www.modernizr.com/download/. Chapter 1 23 Designing for mobile Target browser: all For desktop design, one tends to use either fixed or fluid layout. On the mobile devices, one should almost always use fluid layout. Fluid layout could make your site responsive to browser resize. Getting ready Now create two empty HTML files in your text editor, name one of them ch01r06_a.html and the other ch01r06_b.html. How to do it... 1. In ch01r06_a.html, enter the following code and save the file:

Title here

Footer links here
2. In ch01r06_b.html, enter the following code and save the document:

Title here

Footer links here
HTML5 and the Mobile Web 26 How it works... When you view the two sites in portrait mode, they both look pretty much the same: Now try rotating your screen and see what happens. As you can see now, in landscape mode, the first example renders with spaces at the left and right side, and the second example covers most of the space of the screen: Chapter 1 27 The second example shows a different result: HTML5 and the Mobile Web 28 This site page looks very awkward in a fixed layout, but looks normal in a fluid layout. So when you design for mobile, always remember that your site should be designed with this flexibility. The reasons are: ff Mobile has both portrait and landscape mode ff Mobile has very limited space, so you should use every pixel available on the screen There's more... CSS media queries is also an essential part of responsive design. It assists you with the flexibility of mobile design.
When rendered in a narrower screen, the two sections will be laid out vertically, when rendered in a wider screen, the two sections will be laid out horizontally. The technique we used to make this happen is by using CSS media queries. As in this example, we used @ media screen and (min-width: 480px) {..}, so what it means is that the page is rendered on a page that has a minimum width of 480px, the styles within will be applied: HTML5 and the Mobile Web 30 Now let's see it in orientation mode, as shown next. The two boxes are now next to each other. Desktop-first site Apart from the idea of building a purely mobile or desktop site, there have also always been other ways. One of those is to build a desktop site first, and make it degrade gracefully in mobile. Mobile-first site Another approach is to build it 'mobile first' but make it render gracefully on the desktop. One such approach uses the following in the CSS: @media only screen and (min-width: 320px) { /* Styles */ } @media only screen and (min-width: 640px) { /* Styles */ } @media only screen and (min-width: 800px) { /* Styles */ } @media only screen and (min-width: 1024px) { /* Styles */ } Chapter 1 31 One web approach A third approach is to have a 'one web' version, by which, instead of focusing on mobile or desktop, you focus on both. Defining a content strategy Target browser: all With the data you gathered from the analytics tools, you can define a strategy towards what you want to build. This is particularly useful if you already have a desktop version of the website. Getting ready Make sure you already have JavaScript embedded on your site. How to do it... 1. Go t o your analytics tool and click on Visitors | Mobile under the left navigation: HTML5 and the Mobile Web 32 2. No w if you click on Mobile Devices, you can see the most common devices that people use to surf your site: How it works... Google Analytics can help in finding out the most commonly used mobile devices accessing your site, and also find out the most popular sections of your website. There's more... You can also determine what are the most useful pages on your mobile site. People treat mobile surfing differently from desktop surfing. For instance, if you are running a local store selling products, most people on a tend to surf pages like Contact Us, Location, and Services mobile device. Conversely, on a desktop, people tend to search for Product Catalog, About, and Product Description. Google Analytics can help you find out which are the most visited sections/pages on your site. Apart from Google Analytics, you can also use PercentMobile, as we saw earlier. Chapter 1 33 Browser grade Using an analytics service is one way to decide which devices you want to support. Another way is to use browser grade to know what category you should be targeting. jQuery Mobile has an awesome grid support chart at http://jquerymobile.com/gbs/. There is also a slide on jQuery Mobile that talks about the overall strategies regarding mobile browser web development at http://www.slideshare.net/jeresig/testing- mobile-javascript. Mobile matrices I have been collaborating with Jonathan Neal, and many others, on Smartphone frontend matrices. You can have a look at: https://github.com/h5bp/mobile-boilerplate/wiki/Mobile-Matrices It contains information about most Smartphones in the market, their screen dimensions, DPI, and operating systems. 2 Mobile Setup and Optimization In this chapter, we will cover: ff Adding a home screen button icon ff Preventing text resize ff Optimizing viewport width ff Fixing Mobile Safari screen scale ff Launching phone-specific programs from the browser ff Enabling iPhone start screen in full screen mode ff Preventing iOS from zooming onfocus ff Disabling or limiting WebKit features Introduction While there are many operating systems (OS) as well as device makers, inevitably there could be cross-browser issues that cost us a lot of headaches. But on the other hand, we developers love the challenges and set out to tackle them! Throughout this chapter, we will first focus on cross-browser/browser-specific setup and optimizations you may want to consider. We will then go on to look at a couple of general/ browser-specific features you may want to add at the start of your mobile development. Mobile Setup and Optimization 36 Adding a home screen button icon Target devices: iOS, Android, Symbian On modern smartphones, screens are mostly touch based. The iPhone revolutionized the way we think of mobile by making everything on your device an "app"; even SMS and phone dialing behave like apps with an icon on the home screen. For an HTML web app, things are a bit different; users have to go to a browser app first, type in the address and then launch your site. This can be too much hassle from a user perspective, so on certain smartphones, users can bookmark a home screen icon to a particular web app, so they can launch that particular web app site directly from the icon on their home screen. That sounds cool, right? Yes, it does, but there are also issues associated with it. Not all browsers behave the same way when it comes to touch icons. In this recipe, we will examine the behavior of each browser and how to make home screen icons available to as many mobile browsers as possible. Getting ready First, you have to download the icon sets from the chapter code folder. If you open up the folder, you should be able to see the following: apple-touch-icon.png apple-touch-icon-57x57-precomposed.png apple-touch-icon-72x72-precomposed.png apple-touch-icon-114x114-precomposed.png apple-touch-icon-precomposed.png These images will be used for different devices. Create an HTML document and name it ch02r01.html. How to do it... In your HTML document, use the following code: Mobile Cookbook Chapter 2 37 How it works... Now let's break down the code: As of iOS 4.2.1, it's possible to specify multiple icons for different device resolutions by using the sizes attribute. For high resolution retina displays on iPhone 4, a 114 x 114 icon is used. For iPad, a 72 x 72 icon can be used. For non-retina iPhone, Android 2.1+ devices, a 57 x 57 low resolution icon is used. For Nokia Symbian 60 devices, a shortcut icon is used in link relation to tell the device about the shortcut icon. Mobile Setup and Optimization 38 Here is what the bookmark looks like on Android: There's more... There must be a couple of questions in your mind after seeing the previous example: ff Isn't it possible to define more than one value in the rel attribute? So can we combine the last two lines into something as follows? It was tested, but somehow mobile browsers couldn't recognize the value. You might have seen people use: Together with Paul Irish and Divya Manian, we have been working on Mobile Boilerplate (http://www.h5bp.com/mobile) that provides a rock-solid default for frontend mobile development. In Mobile Boilerplate, we have covered all the current scenarios and possible future scenarios: https://github.com/h5bp/mobile-boilerplate/blob/master/index.html#L21 Chapter 2 39 Everything you always wanted to know about touch icons Most ideas presented on this topic are originated from Mathias Bynens. His original article Everything you always wanted to know about touch icons can be found at: http://mathiasbynens.be/notes/touch-icons. Official documentation about Apple touch icons There is a list of official documentation where you can find more information about touch icons for each specific device and browser: ff Apple touch icon: http://developer.apple.com/library/safari/#documentation/ AppleApplications/Reference/SafariWebContent/ ConfiguringWebApplications/ConfiguringWebApplications.html ff Official information from WHATWG: http://www.whatwg.org/specs/web-apps/current-work/multipage/ links.html#rel-icon Apple Custom Icon and Image Creation Guidelines Guidelines and articles about how to create a touch icon can be found at the following article: ff Apple – Custom Icon and Image Creation Guidelines: http://developer.apple.com/library/ios/#documentation/ userexperience/conceptual/mobilehig/IconsImages/IconsImages. html#//apple_ref/doc/uid/TP40006556-CH14-SW11 See also Enabling iPhone start screen in full screen mode – in this recipe, we will see how to add a start screen in full screen mode when launched from the home screen touch icon. Preventing text resize Target devices: iOS, Windows Mobile On certain mobile devices like the iPhone and Windows Mobile, browser text may resize when you rotate the device from portrait to landscape mode. This could be problematic to web developers because we want to have full control of the design and rendering of the website. Mobile Setup and Optimization 40 Getting ready Create a new HTML file, and name it ch02r02.html. Enter the following code:
HTML5 Logo
HTML5 Badge
It stands strong and true, resilient and universal as the markup you write. It shines as bright and as bold as the forward-thinking, dedicated web developers you are. It's the standard's standard, a pennant for progress. And it certainly doesn't use tables for layout.
Chapter 2 41 Now render this page in portrait mode in iPhone, as you can see, it will be rendered normally as follows: Now if you render it in the landscape mode, the font size will suddenly increase. As we can see when the page is changed to landscape mode, the text will get resized. This is not the desired behavior. The following shows how it looks: Mobile Setup and Optimization 42 How to do it... You can follow these steps to fix the issue: 1. You can add the following lines to the CSS, and then render the page in landscape again: html { -webkit-text-size-adjust: none; } 2. As Y ou can see, the text now appears normal: How it works... To solve this issue, you have to add a CSS property named text-size-adjust in WebKit, and assign the value to none to prevent the auto adjust. Setting text-size-adjust to none solves the problem for mobile-specific websites, but if we render this on a desktop screen or other non-mobile browser, the desktop browser text zoom feature will be disabled. To prevent this accessibility issue, we can set text-size- adjust to 100% instead of none. So we can tweak this example to: html { -webkit-text-size-adjust: 100%; } Chapter 2 43 There's more... Apart from iPhone, other devices also have ways to add the text size adjust property. Windows Mobile Windows Mobile IE uses a different prefix. They originally added the WebKit prefix. The intent was adding support for the WebKit-specific property to make web developers' lives a bit easier by not having to add yet another vendor-prefixed CSS property to their pages to control how text was scaled. Even more specifically, they intuited that the most common use case for this property was to explicitly set it to none in order to tell the browser not to scale a particular section of the text. After hearing the community's feedback on this issue (and a couple of face-plants when they realized the broader implications of implementing other browser vendors' CSS properties) they've decided that it's best to only implement the -ms- prefixed version and not the -webkit- one. So to make the preceding example more complete, you can add: html { -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; } Making it future proof To make things more future proof, you can add one more line without any prefix, as follows: html { -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; text-size-adjust: 100%; } px em, which is better? The common debate about using px versus em is less of a problem on mobile. Originally Yahoo! User Interface used ems for the reason that IE6 doesn't support page zoom with pixels. On mobile, there isn't such an issue, and even if we want the page to render well on desktop browsers, the likelihood of someone using IE6 is getting lower and lower, so in most cases, you can save the trouble of using ems and all the calculation, and choose instead to use pixels. Mobile Setup and Optimization 44 Optimizing viewport width Target device: cross-browser Different mobile devices have different default mobile viewport widths. Refer to Appendix X for a complete list of default viewport widths for all mobile devices. If you leave it unset, in most cases, it will cause an unexpected result. For example, in an iPhone if the viewport width is left unset, it will be rendered as 980 px. Getting ready Let's create an HTML document and name it ch02r03.html. How to do it... Here is what we can do to optimize the viewport width: 1. Add the following code to ch02r03.html and render it in your mobile browser:
HTML5 Logo

Lorem ipsum

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Chapter 2 45 Here is how it's rendered by default: 2. If w e render this example, we can see that everything becomes extremely small. Now, let's set the viewport width to the device width:
HTML5 Logo
Mobile Setup and Optimization 46

Lorem ipsum

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Now the content width uses the screen width and the text becomes readable: How it works... When we set viewport width to device-width, it will tell the browser not to scale the page to fix the device area. So for iPhone, the device-width is 320 px in portrait mode and 480 px in landscape mode. Chapter 2 47 There's more... For some really old relic mobile browsers, the meta attribute isn't recognized. To deal with these browsers, you need to use: This is used by older versions of Palm OS, AvantGo, and Blackberry. For Microsoft PocketPC, a MobileOptimized attribute was introduced. So the most complete code should look like: IE for Windows Phone viewport blog post On IE for Windows Phone Team Weblog, there is an article about IE Mobile Viewport on Windows Phone 7. In it, the author has explained important information like how Windows Phone 7 implements "device-width", together with much other very useful information in general. You can read the article here: http://blogs.msdn.com/b/iemobile/ archive/2010/11/22/the-ie-mobile-viewport-on-windows-phone-7.aspx. Safari documentation Safari has a reference in the developer's library at: http://developer.apple. com/library/safari/#documentation/appleapplications/reference/ SafariHTMLRef/Articles/MetaTags.html. Blackberry documentation There is a Blackberry Browser Content Design Guidelines document. It explains Blackberry's use of viewport width: http://docs.blackberry.com/en/developers/ deliverables/4305/BlackBerry_Browser-4.6.0-US.pdf. Mobile Setup and Optimization 48 Fixing Mobile Safari screen re-flow scale Target device: iOS Mobile Safari has an annoying screen re-flow bug: When you rotate the mobile browser from portrait mode to landscape mode, the text will suddenly jump to a bigger size. During the time I was working on building Mobile Boilerplate, Jeremy Keith and I had a long discussion on this issue. The traditional way of fixing this is to add the following scaling attributes to the meta viewport: This solution was first incorporated into Mobile Boilerplate. Jeremy pointed out that this solves the scale jump problem, but at the same time, it causes another issue with accessibility: When you set the values as shown above, you can no longer zoom the page to enlarge it. For people with eyesight problems, the ability to zoom is essential. But if we let the zoom happen, the text jump will annoy the majority of the users. So, for a long time it was an accessibility versus usability debate. I discovered a method that could tackle the issue and we will discuss this next. Getting ready First, let's create an HTML document and name it ch02r04.html, enter the following code in it:

Lorem ipsum

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Chapter 2 49 This page renders perfectly fine in portrait mode: But when displayed in landscape mode, things change: Mobile Setup and Optimization 50 How to do it... All we need to do to solve this problem is to dynamically reset the scale factors to default when the user zooms in on the page. Now put the following code in your HTML document:

Lorem ipsum

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Chapter 2 51 Now if we rotate the screen from portrait to landscape, the issue should no longer exist, and if we zoom in on the page, it will react as expected: How it works... Let's have a walk through of the code to see how it works. 1. We need to know the default minimum-scale and maximum-scale values. In the iPhone's official documentation, it states that the minimum-scale value is 0.25, and the maximum-scale value is 1.6. So to replace the default value, we need to set: function gestureStart() { var metas = document.getElementsByTagName('meta'); var i; for (i=0; i if (metas[i].name == "viewport") { metas[i].content = "width=device-width, minimum- scale=0.25, maximum-scale=1.6"; } } 2. Ne xt, we need to know when to set this. This is very easy: The iPhone has a gesture event listener we can use to target the document body. Here is how to do so: document.addEventListener("gesturestart", gestureStart, false); 3. Finally , we need to make sure this only happens on iPhone. Again this can be easily done using: if (navigator.userAgent.match(/iPhone/i)) { document.addEventListener("gesturestart", gestureStart, false); } Mobile Setup and Optimization 52 There's more... If you are interested to know the whole story and discussion between Jeremy and I, you can read it at http://www.blog.highub.com/mobile-2/a-fix-for-iphone-viewport- scale-bug/. Even though this provides a fix for the issue, there are a couple of problems that some people experience: ff As soon as the user makes a gesture on the document, zooming is enabled again. So if you change the device orientation after that, the zoom bug will still occur. ff It's reported on iOS4 that users can only effectively start zooming after starting a second gesture. A slightly improved version Mathias Bynens has a revised version with smarter coding. You can see the code at https://gist.github.com/901295. An even better version John-David Dalton had an even better updated version with smarter and leaner code at https://gist.github.com/903131. A word for jQuery Mobile Scott Jehl from jQuery Mobile mentioned it might be implemented in jQuery Mobile in the future. Currently, you could see his gist at https://gist.github.com/1183357. Launching phone-specific programs from the browser Target device: cross-browser One can launch phone-specific programs from the mobile browser such as Maps, Call, and SMS can be launched from certain mobile devices. Whether the program can be launched depends on the availability of the native application on the particular device. Chapter 2 53 Getting ready Create an HTML document and name it ch02r05.html. How to do it... Here is how we could launch a phone-specific program: 1. Let's add the following code to the HTML document:
HTML5 Logo

Lorem ipsum

Directions
Mobile Setup and Optimization 54 2. No w run this code in Palm OS browser, press the address link. You will be prompted to launch the map application on your phone: How it works... Unlike some schemes, map URLs do not start with a "maps" scheme identifier. Instead, map links are specified as regular HTTP links, but are targeted at the Google Maps servers. The device browser will be able to tell if it's a map and launch the program with the information parsed. There's more... You can do more than just launch an application. The following examples show the strings you would use to provide driving directions between San Francisco and Cupertino: Directions Chapter 2 55 So, what if a browser can't launch a specific program? That's ok! In this case it will just open as a normal link: Mobile Safari URL scheme A list of all Mobile Safari-related URL schemes can be found at: http://developer. apple.com/library/safari/#featuredarticles/iPhoneURLScheme_Reference/ Introduction/Introduction.html. Blackberry URL scheme A list of all Blackberry-related URL schemes can be found at: http://docs.blackberry. com/en/developers/deliverables/18169/. Sony Ericsson developers' guidelines Sony Ericsson developers can download Web Browsing Developer Guidelines from the Developer World site at: http://developer.sonyericsson.com/wportal/devworld/search-do wnloads?cat=%5B1.706817%2C+1.716594%2C+1.716688%5D&cc=gb&lc=en. Mobile Setup and Optimization 56 Enabling iPhone start screen in full screen mode Target-device: iOS To make a web app feel more like a native app, the iPhone has quite a few unique features for developers to add on web apps. You can add start screen in full screen mode, and style the status bar, as well as defining a pre-load screen for the app. Getting ready Download the images in the source code provided, create an HTML document, and name it ch02r06.html. How to do it... Here is how we can make the start screen in full screen mode: 1. Enter the following HTML code:
HTML5 Logo
Lorem ipsum
2. If y ou bookmark the page and open it in the browser from the app icon, it will display as a full-screen app. Chapter 2 57 How it works... Let's go through the code: This makes the web page run in full screen mode when launched from the home screen icon, hides the address bar and component bar at the browser's top and bottom. This styles the status bar at the top of browser. You can also add a splash screen when the app launches, which is a preload screen displayed while the page is still loading. There's more... iPad and iPhone have different splash screen sizes, so if we want the site to dynamically change the splash screen, this depends on the browser used to render. We can use the following JavaScript function to do this: var filename = navigator.platform === 'iPad' ? 'h/' : 'l/'; document.write('' ); Full screen issue with iOS 4.3 iOS 4.3 introduced a new feature which they call the JavaScript Nitro Engine. This new code allows the default Safari browser to load pages up to twice as fast. However, this feature didn't seem to be supported by full screen web applications. While some question why Apple didn't incorporate the new Safari feature with its web applications, others also point to evidence that it might just be a bug. Safari documentation about web applications For the official documentation, you can visit the site on Safari at: http://developer.apple.com/library/safari/#documentation/ appleapplications/Reference/SafariWebContent/ ConfiguringWebApplications/ConfiguringWebApplications.html Mobile Setup and Optimization 58 Safari splash image and touch icon guidelines For splash image and touch icon guidelines, you can visit Custom Icon and Image Creation Guidelines on the official Safari site: http://developer.apple.com/library/safari/#documentation/ UserExperience/Conceptual/MobileHIG/IconsImages/IconsImages.html#// apple_ref/doc/uid/TP40006556-CH14 Prevent iOS from zooming onfocus Target device: iOS In JavaScript events API, there is a form onfocus event. When you tap on a form element in iOS, the element will zoom in on the device screen. For a site not designed to be responsive or mobile-specific, such default zooming can be helpful, but for a site that is mobile optimized, this could be less helpful and can be annoying. To disable this default behavior, we could change the meta viewport value onfocus and onblur. Getting ready Create an HTML document and name it ch02r06_b.html. How to do it... Here is how we could launch a phone-specific program: 1. Let's add the following code to the HTML document:

2. No w, render the page in the iOS devices, touch focus the form input field, and as you can see, now the input field won't zoom in. How it works... Now let's extract out the JavaScript portion: What the script does is when the onfocus event is detected, we set the maximum-scale to 1 and when onblur is detected, we set it to 10. There's more... You can read more about the original blog post discussion at: http://nerd.vasilis.nl/prevent-ios-from-zooming-onfocus/ This code snippet was added to Mobile Boilerplate: https://github.com/h5bp/mobile-boilerplate/blob/master/js/mylibs/ helper.js Disabling or limiting WebKit features Target-device: WebKit mobile browsers (Android, iOS) There are many device-specific issues in mobile browsers. With a few less-known CSS techniques, we could tackle these issues easily. Let's take a look at some of the issues and how we can magically get them fixed. Mobile Setup and Optimization 60 Getting ready Create an HTML document and name it ch02r07.html. How to do it... Here is an example of how to limit the WebKit feature: 1. Add the following code into the HTML document: Chapter 2 61 2. No w, enter the additional code to the HTML document, Mobile Setup and Optimization 62 How it works... Without setting webkit-touch-callout, when you tap and hold a link on your device, there will be a prompt asking you if you want to open it in the current page, open it in the new page or copy, as shown in the first example. If you want to disable this feature, you can do so by setting webkit-touch-callout value to none, as shown in the second example. There's more... Another feature you might want to limit is the copy-and-paste. This feature makes sense on a web page, but for most interface elements of an application it is not wanted. Changing the tap color You can change the tap color by using the following rule: Making text area content editable If you want to have an element as contenteditable, you can use the following CSS: textarea.contenteditable { -webkit-appearance: none; } Ellipsis for the narrow screen On mobile browsers, the screen is much narrower, so when you are displaying a menu title list, text overflow may occur. If this happens, a CSS trick could help you fix text overflow with ellipsis: .ellipsis { text-overflow: ellipsis; overflow: hidden; white-space: nowrap; } 3 Interactive Media with Mobile Events In this chapter, we will cover: ff Moving an element with touch events ff Detecting and handling orientation event ff Rotating an HTML element with gesture events ff Making a carousel with swipe events ff Manipulating image zoom with gesture events Introduction One of the biggest differences between mobile and desktop is the way in which we interact with the screen. On a desktop screen, we use a mouse to move and click events to control the interaction. On a mobile screen, the interaction comes from touch and gesture events. In this chapter, we will see some of the events that are unique to touch screens (for example, two finger events) and how you can leverage these features to build something unique for mobile. Moving an element with touch events Target device: cross-browser On a mobile screen, we interact with elements using touch events. Because of that, we can move an HTML element on the screen with our fingers. Interactive Media with Mobile Events 64 Getting ready For this example, we will be using jQuery. First, let's create a new HTML file, and name it ch03r01.html. How to do it... In your HTML document, use the following code: Mobile Cookbook
Chapter 3 65 Now let's see how it renders in Opera: How it works... First, we register the square div with a touchmove event. You can detect the touch position relative to the page which is touch.pageX and touch. pageY in our example. We use the finger position minus half the width and height of the square div element, so it feels like we are moving with the div center as the registration point. var x = touch.pageX - elm.left/2; var y = touch.pageY - elm.top/2; We apply the x and y values to the square element using CSS position. This is the 'moving' action. $(this).css('left', x+'px'); $(this).css('top', y+'px'); There's more... You may have realized that, at the top of this example, there is one line as follows: var touch = e.originalEvent.touches[0] || e.originalEvent. changedTouches[0]; Now you might be wondering what it does. Mobile Safari does not allow the e.touches and e.changedTouches properties on event objects to be copied to another object. You can get around this issue by using e.originalEvent. You could read more about it here: http://www.the-xavi.com/articles/trouble-with-touch-events-jquery. Interactive Media with Mobile Events 66 jQuery mobile events jQuery mobile is a set of components. If you want to dig into all the mobile-related events, you can find them at: https://github.com/shichuan/jquery-mobile/blob/master/js/jquery. mobile.event.js. Zepto Zepto is a more lightweight alternative to jQuery that you could consider using if your main target is WebKit-based browsers. You can find out more about it at: https://github.com/madrobby/zepto. Safari's guide on mobile event handling For the official reference, you could visit Safari's online guide at: http://developer.apple.com/library/safari/#documentation/ appleapplications/reference/safariwebcontent/HandlingEvents/ HandlingEvents.html. See also ff Redrawing a canvas with orientation events ff Rotating an HTML element with gesture events ff Making a carousel with swipe events ff Manipulating image zoom with gesture events Detecting and handling orientation event Target device: cross-browser On mobile browsers, if your site is built based on a fluid layout, it shouldn't be affected by orientation change. But for a highly interactive site, sometimes you may want to handle orientation change in a special way. Getting ready Create a new HTML file, and name it ch03r02.html. Chapter 3 67 How to do it... Now let's start creating the HTML and Script to detect and handle orientation event. 1. Enter the following code: Mobile Cookbook
2. No w, render this code in your mobile browser and rotate the screen to view in both portrait and landscape mode. In portrait mode, the text output will be 'PORTAIT'. Chapter 3 69 3. When we rotate the screen to landscape mode, the text will be 'LANDSCAPE'. How it works... By listening to window.onorientationchange event, we could get the orientationchange event, when it occurs; we get the event.orientation parsed to the function to output the result. There's more... At times, you may want to lock the orientation of the screen if let's say when building a game. For a native application, this can be easy, but for a web app, this can be a bit difficult to achieve. Let's create a one-page screen that locks to only landscape mode. Note that this is a proof-of-concept, and to create really sophisticated apps or game requires more calculation and handling. Create a document and name it ch03r02_b.html, and enter the following code Mobile Cookbook
enter the game
Interactive Media with Mobile Events 72 Now if you render the page in your browser, you will see the following screen. In portrait mode, it suggests to the user the game/application is designed to be viewed in landscape mode: When you rotate the screen from portrait to landscape mode, it looks normal: Chapter 3 73 In this example, we used transform:rotate from CSS3 to rotate the screen to 90 degrees when viewed in portrait mode: #screen { text-align:center; -moz-transform:rotate(90deg); -webkit-transform:rotate(90deg); -o-transform:rotate(90deg); -ms-transform:rotate(90deg); } The mode the user is in can be determined by window.orientation. There are four values: -90, 0, 90, 180. The device is in landscape mode when the degree is -90 and 90. And it's in portrait mode when the degree is 0 and 180. switch(window.orientation) { case 0: // Portrait case 180: // Upside-down Portrait //... break; case -90: // Landscape: turned 90 degrees counter-clockwise case 90: // Landscape: turned 90 degrees clockwise //... break; } With this, you can determine the orientation of the screen. Safari's native support For the official reference, you could visit Safari's online guide at: http://developer.apple.com/library/safari/#documentation/ appleapplications/reference/safariwebcontent/HandlingEvents/ HandlingEvents.html. Web versus native Although mobile web is catching up, if you are developing a highly interactive application, always keep in mind that even the slowest native app still performs faster than an HTML app. If you are deciding to use HTML5 to build an app, you also have to keep all the hacks and browser inconsistencies in mind. Interactive Media with Mobile Events 74 See also ff Moving an element with touch events ff Rotating an HTML element with gesture events ff Making a carousel with swipe events ff Zooming an image with gesture events Rotating an HTML element with gesture events Target device: iOS, Android, Symbian On Mobile Safari, you can detect the degrees of rotation when people use two fingers to do a rotation on the screen. Because of that, we can use our fingers to rotate an element on the screen! Getting ready Let's create an HTML document and name it ch03r03.html. How to do it... 1. A dd the following code to ch03r03.html and render it in your mobile browser: Mobile Cookbook
Interactive Media with Mobile Events 76 2. No w use two fingers to rotate the box and you will see something like this: How it works... In this example, we rotate the element when there is an ongesturechange event triggered. We get the rotation degree by using the following value: e.target.rotation There's more... You may have noticed that we also listen to ongestureend event, because if the user has previously rotated, this script will remember the last rotated angle and continue to rotate from there. Safari event handling For the official reference, you could visit Safari's online guide at: http://developer.apple.com/library/safari/#documentation/ appleapplications/reference/safariwebcontent/HandlingEvents/ HandlingEvents.html. Chapter 3 77 CSS3 transforms In this example, we used CSS3's transforms feature. You can find more information about WebKit and CSS transform at WebKit's blog at: http://www.webkit.org/blog/130/css-transforms/. Drawbacks of the scale bug fix In this example, we used maximum-scale=1.0 to prevent zooming when using a gesture event. This will cause some accessibility drawbacks, so use a rotate event only if you are building a highly interactive web application. Try to avoid it when building a mobile website. See also ff Moving an element with touch events ff Redrawing a canvas with orientation events ff Rotating an HTML element with gesture events ff Zooming an image with gesture events Making a carousel with swipe events One of the common features of mobile devices is swiping. When you browse photos in your photo gallery, you swipe left and right to navigate from one picture to another. On Android devices, you swipe down to unlock the phone. On a mobile browser, you can use swipe as well. Getting ready First, let's create an HTML document and name it ch03r04.html. How to do it... 1. Ent er the following code: Mobile Cookbook
Chapter 3 79
Interactive Media with Mobile Events 80 2. Once y ou've entered the code in the page, swipe left and right of the viewing area, and you can see the boxes being scrolled horizontally: How it works... We have used a couple of HTML5 techniques in this example. First, we used jQuery Mobile to detect the swipe event. When we use our finger to swipe the page to the left or right, an event listener is assigned: $('#wrapper').swipeleft(function () { }); $('#wrapper').swiperight(function () { }); When the swipe events are detected, jQuery animation .animate() is used to create the moving effect: $('#inner').animate({ left: '+=210' }, 500, function() { // Animation complete. curNum -=1; $('.full-circle').removeClass('cur'); $('.full-circle').eq(curNum).addClass('cur'); }); Chapter 3 81 There's more... In this example, we used a CSS3 technique for the circle buttons. You can draw an entire circle using just pure CSS3: .full-circle { background-color: #ccc; height: 10px; -moz-border-radius:5px; -webkit-border-radius: 5px; border-radius: 5px; width: 10px; } In this example, we define the width and height of the document to be 10 px, and the border radius to be 5 px. Now you can have a perfect circle in just a couple of lines of CSS! Zepto framework and swipe events You can use the Zepto framework to do something similar. It has events such as swipe, swipeLeft, swipeRight, swipeUp, swipeDown. YUI and gesture events YUI has gesture events which you can use to create swipe events. You can read more about this here: Supporting A Swipe Left Gesture: http://yuiblog.com/sandbox/yui/3.3.0pr3/examples/event/ swipe-gesture.html Dive into the source Events in jQuery mobile are built in a modular way. Those who want to learn how jQuery made the swipe event can visit: https://github.com/jquery/jquery-mobile/blob/master/js/jquery.mobile. event.js. The part related to swipe events is under: $.event.special.swipe = {…} Vertical, horizontal, and distance threshold are calculated for the event calculation. See also ff Moving an element with touch events ff Redrawing a canvas with orientation events ff Rotating an HTML element with gesture events ff Zooming an image with gesture events Interactive Media with Mobile Events 82 Zooming an image with gesture events On the iPhone, you can resize an element based on zoom detection. On gesture change, you could get the value of the scale factor, and zoom HTML elements based on it. Getting ready Create an HTML document and name it ch03r05.html. How to do it... Enter the following code: Mobile Cookbook
How it works... In this example, we assign the element we want to scale with the ongesturechange event. The scale factor is determined by the e.target.scale: width *= e.scale; height *= e.scale; There's more... Gesture events can be tricky, so using them properly is very important. For a two finger multi-touch gesture, the events occur in the following sequence: 1. touchstart for finger 1. Sent when the first finger touches the surface. 2. gesturestart. Sent when the second finger touches the surface. 3. touchstart for finger 2. Sent immediately after gesturestart when the second finger touches the surface. 4. gesturechange for current gesture. Sent when both fingers move while still touching the surface. 5. gestureend. Sent when the second finger lifts from the surface. 6. touchend for finger 2. Sent immediately after gestureend when the second finger lifts from the surface. 7. touchend for finger 1. Sent when the first finger lifts from the surface. Official iOS Safari guide on GestureEvent There is an official iPhone Safari guide that explains the details of GestureEvent class on Safari: http://developer.apple.com/library/safari/#documentation/ UserExperience/Reference/GestureEventClassReference/GestureEvent/ GestureEvent.html. Interactive Media with Mobile Events 84 YUI gesture events YUI from Yahoo! has a cross-browser solution for gesture events, but only supports one-finger events. You can find out more about it at: http://developer.yahoo.com/yui/3/event/#gestures. Google Maps and gesture events One example of a site that relies heavily on the two fingers gesture event is Google Maps on Mobile Safari: See also ff Moving an element with touch events ff Redrawing a canvas with orientation events ff Rotating an HTML element with gesture events ff Making a carousel with swipe events 4 Building Fast and Responsive Websites In this chapter, we will cover: ff Building pages using basic HTML5 markup ff Using CSS3 features for progressive enhancement ff Applying responsive design with media query ff Using dynamic loading ff Applying user agent detection ff Adding mobile bookmark bubble to the home page ff Building Contact page with textarea and autogrow forms ff Making buttons with instant response ff Hiding WebKit chrome ff Building a mobile sitemap Introduction On mobile devices, bandwidth is not always as good as on a desktop computer. If you are on a slow 3G network, things can get loaded much slower than on a Wi-Fi hotspot. Even for Wi-Fi connections, many mobile browsers process slower than desktop computers. So when we create mobile sites, they have to be fast and responsive. Building Fast and Responsive Websites 86 From this chapter onwards, we will also start to introduce HTML5 features. HTML5 is a set of technologies consisting of semantics, new CSS rules and properties, and new JavaScript APIs which could be used to build better structured web pages and powerful web applications. The following are the eight main HTML5 features: ff Semantics ff Offline and storage ff Device access ff Connectivity ff Multimedia ff 3D, graphics, and effects ff Performance and integration ff CSS3 Not all of these features are mobile exclusive; some are related more to mobile web, while some are more general for both mobile and desktop web. We will talk about each of these features and see how best they could help with our mobile development. Based on the examples created using the new semantic tags and CSS3, we will discuss many ways to fully leverage what the mobile browser is offering and how to build a website using these unique features. Building pages using HTML5 semantics Target device: cross-browser HTML5 introduced a richer set of tags; these tags give meaning to structure. Semantics is a fundamental aspect of HTML5. We won't be going through all the tags here, but will cover some of the most commonly used ones. Getting ready First, let's create a new HTML file, and name it ch04r01.html. Let's create a fictional site about music. Chapter 4 87 How to do it... In our HTML document, type in the following code: first.fm

first.fm

© 2011 first.fm
How it works... The header element is often used for h1 to h6 elements; it could appear as the head of the entire page or the head of any block-level element. It often contains a title, subtitle, or tagline.
element:
Building Fast and Responsive Websites 88 The nav element represents navigation for a document. The nav element is a section containing links to other documents or to parts within the current document. Not all groups of links on a page need to be in a nav element. It's only groups of primary or secondary navigation links. In particular, it is common for footers to have a list of links to various key parts of a site, but the footer element is more appropriate in such cases.