Over a million developers have joined DZone.
Refcard #186

HTML5 Mobile Development

Important HTML5 Mobile Technologies, Tools, Frameworks, and Communities

by Maximiliano Firtman

Covers the most important HTML5 mobile technologies and is intended to bring you up to speed in mobile HTML5 development.

Free PDF
HTML5 Mobile Development
Section 1

Basics: What is a Viewport?

A viewport allows us to normalize different devices to get the best sizes for a mobile website or webapp and to avoid initial zooming.

All platforms support viewport definitions through <meta> tags:

<meta name="viewport" content="{comma-separated options}">

The most useful version is

<meta name="viewport" content="width=device-width"

Viewport Options

Option Values
width Width of the virtual viewport that the browser will expose to our website in CSS pixels or the constant device-width
height Height of the virtual viewport that the browser will expose to our website in CSS pixels or the constant device-width
user-scalable no/yes
initial-scale Float value (1=no zoom)
minimum-scale Float value
maximum-scale Float value
target-densitydpi Integer value (70 to 400) in DPI or one of the following constants: device-dpi, high-dpi, medium-dpi, low-dpi. Not available on Safari for iOS

Viewport Through CSS

Internet Explorer since v10 also supports @viewport on CSS:

@-ms-viewport {
     width: device-width;

On Windows 8, including tablets, IE can work in snap state. We can define the viewport only when in this mode:

@media screen and (max-width: 400px) {
@-ms-viewport { width: 320px; }

Device-Width Values

When using width=device-width as the viewport's width, the final width that we'll have available may be (measured in CSS pixels):

Option Values
320 The most common value on smartphones including iPhone, Windows Phone, Android (medium screen sizes < 4")
360 Large screen Android smartphones (< 5"), such as Galaxy SIII & SIV
400 Phablets (>5"), such as Galaxy Note
600 Small tablets
768 Large tables

Even on high-resolution screens, such as Retina displays, you will always get a width in CSS pixels with a value of 320. Therefore, the available width for the canvas is the same for all devices.

Landscape viewport

Safari for iPhone will not use the available space on the viewport on landscape and it will zoom in the content. To avoid this behavior we can use the code on https://gist.github.com/901295

Section 2

Mobile URLs

Using standard hyperlinks we can communicate with the operating system. Remember to encode in URL format any parameter that you might pass through.

Calls and Messaging

To initiate a call, tel:{phone-number}

<a href="tel:+14152110022">Call us</a>

To initiate an SMS, sms:{destination}?body={message}. The body might be ignored by some platforms.

<a href="sms:1111?body=Hello">Send us SMS</a>

To initiate a mail compose, mailto:{to}?subject={subject}&body={message} iOS supports HTML on the body.

<a href="mailto:user@domain.com?subject=Hello?">Send us SMS</a>

To initiate a Facetime call on iOS, facetime:{number/user}

<a href="facetime:myuser">Call us with Facetime</a>

To initiate a Skype call, skype:{user}?call

<a href="skype:myuser?call">Call us with Skype</a>

To tweet through the native Twitter app, twitter://post?message={message}

<a href="twitter://post?Hello">Tweet</a>

To open the Maps app on Android and iOS < 6, http://maps.google.com?q={query}

<a href="http://maps.google.com?q=golden+gate+bridge">Open Map</a>

To initiate a navigation on Android and iOS < 6, http://maps.google.com?saddr={point1}&daddr={point2}

<a href="http://maps.google.com?saddr=golden+gate+bridge
&daddr=Pier+39">Navigate to Pier 39</a>

To open the Maps app on iOS >=6, http://maps.apple.com?q={query}

<a href="http://maps.apple.com?q=golden+gate+bridge">Open Map</a>

To initiate a navigation on iOS >= 6, http://maps.apple.com?saddr={point1}&daddr={point2}

<a href="http://maps.apple.com?saddr=golden+gate+bridge
&daddr=Pier+39">Navigate to Pier 39</a>

Apple Stores

To open iTunes, AppStore or iBookStore on iOS, generate the link from https://itunes.apple.com/linkmaker

To Remove Automatic Linking

<meta name="format-detection" content="telephone=no">
<meta name="x-rim-auto-match" content="none" forua="true">

Section 3

High Resolution Support

Devices with a high-resolution display (as in Retina iOS devices) will use a multiplier for all your dimensions, known as device pixel ratio. Therefore, if you draw a 100 pixels element it will render as a 100 device pixels on a device with an average screen density, it will be rendered as 200 real pixels on a high resolution device such as iPhone 5, and it will be rendered as a 300 real pixels on a ultra high resolution device, such as Samsung Galaxy SIV.

Thanks to the device pixel ratio, our design will look the same in inches on every device, regardless of the screen density.

Using Scalar Solutions

Using these techniques, our content will render properly on all kinds of screen densities without image quality loss:

SVG: Scalable Vector Graphics

We can use SVG as an external document or as inline using the <svg> new element

Font face

We can use font files for iconography in conjunction with CSS3 Font face. Look at fontello.com and icomoon.io


Use CSS3 for effects, gradients, rounded corners and backgrounds

Providing Alternate Bitmap Files

When working with bitmap files (JPEG, GIF, PNG), we can provide different versions of the same file for different resolution. Be careful about the final size for high-resolution devices.

Using background images and media queries

If bitmap images are defined using background images on CSS, we can provide alternate versions using the extension (prefixed) device-pixel-ratio. For devices with a pixel ratio of 2 or more:

/* Low resolution version */
#picture {
      background-image: url(picture_low.png);

/* High resolution version with different prefixes */
@media screen and (min--moz-device-pixel-ratio: 2),
    only screen and (-webkit-min-device-pixel-ratio: 2) {

#picture {
                background-image: url(picture_hi.png);
                    background-size: 100%;

Using image-set

On Safari for iOS from version 6 we can use the -webkit-image-set function to provide different images from CSS:

background-image: -webkit-image-set( 
url(picture_low.png) 1x,
                        url(picture_hi.png) 2x 

Using JavaScript

We can query the window.devicePixelRatio property. If it's undefined, we can guess a low-resolution device; if it's a numeric value we can use it to change the image being loaded.

var pixelRatio = window.devicePixelRatio || 1;

if (pixelRatio >= 2) {
     document.querySelector("#image1").src = "picture_hi.png";
Section 4

Mobile Icons

We need to provide different icons for the tab or title area and for the home screen when the user adds an icon to it. Different platforms and devices support different icon sizes.

Window and Tab Icons

<link rel="icon" href="icon_32.png">
<!-- For IE, we need an icon in ICO format -->
<link rel="shortcut icon" href="icon.ico">

Home Screen Icons

<-- iPad icons -->
<link rel="apple-touch-icon" href="icons/72.png" sizes="72x72">
<link rel="apple-touch-icon" href="icons/144.png" sizes="144x144">

<!-- iPhone and iPod touch icons -->
<link rel="apple-touch-icon" href="icons/57.png" sizes="57x57">
<link rel="apple-touch-icon" href="icons/114.png" sizes="114x114">

Other platforms—such as Android, BlackBerry and Symbian—support the apple-touch-icon link with non-standard sizes.

Nokia Symbian also supports:

<link rel="nokia-touch-icon" href="icons/54.png">

Precomposed icons

By default, Apple will add shadow, rounded corners and 3D shine effects to the icons, as in the following image:

To avoid some of these effects we can use the alternate version

<link rel="apple-touch-icon-precomposed" href="icons/72.png" sizes="72x72">

Windows 8 Start Screen Tile

Internet Explorer 10 on Windows 8 supports a "Pin to the Start Screen" feature. We can define the background color and the icon to be used in the Start Screen using:

<meta name="msapplication-TileImage" content="icons/tile144.png">
<meta name="msapplication-TileColor" content="#FFFF00">

Updating a badge notification

The Start Screen Tile may be updated frequently defining an XML URL through:

<meta name="msapplication-badge"

The XML will look like:

<?xml version="1.0 ?>
<badge value="30"></badge>
Section 5

Upgrade to Webapp

A webapp is a hosted website that can be installed with a home screen icon and once installed it works full-screen outside of the browser and it might have some kind of super powers in terms of permissions and support.

iOS Home Screen Webapps

On iPhone and iPad we can create webapps using a meta tag and usually adding the apple-touch-icon link:

<meta name="apple-mobile-web-app-capable" content="yes">

Once added to the Home Screen, a page with the meta tag will open in full screen mode.

We can customize the status bar appearance through one of the possible options on this meta tag:

<meta name=apple-mobile-web-app-status-bar-style" content="{black/default/black-translucent}">

Startup images

When the webapp is opened from the Home Screen, we can define a startup image that acts as the image while the webapp is being loaded:

<link rel="apple-touch-startup-image" href="startup.png">

The image has to be full screen size and because there are several resolutions (iPhone 3GS, iPhone 4S, iPhone 5, iPad Mini, iPad 2) we can use media queries to provide different versions.

For iPhone 5 and latest iPods touch we can use:

<link rel="apple-touch-startup-image" href="startup.png"
media="only screen and (device-height: 568px) and
(-webkit-device-pixel-ratio: 2)">

We can also provide portrait and landscape versions for iPads using orientation: landscape and orientation: portrait in the media attribute.

Opening Links

While in a webapp, all the links are opened in Safari (new window). To open a link and replace the current HTML in our app context, we can use JavaScript as in:

<a href='#' onclick='location.href="newfile.html"'>Go</a>

Mozilla Open Webapps

On Firefox for desktop and mobile, including Firefox OS, we can install a webapp using a manifest JSON file and a JavaScript API.

The manifest file looks like:

"name": "My HTML5 App",
"description": "This is the description of the app",
"launch_path": "/index.html", 
"icons": {
"128": "/img/icon-128.png" // >=128 is mandatory
"default_locale": "en"

To initiate the webapp installation we can use the Apps API:

var r = window.navigator.mozApps.install("/manifest.webapp");
r.onsuccess = function() { 
alert("App installed") 
r.onerror = function() { 
alert("App installed") 
Section 6

Touch Events

Mouse events (such as click) are not always suitable for mobile devices for different reasons, including:
a) A delay of 300ms before firing the event handler.
b) They don't support multitouch.
c) The clickable area using a finger is not always just one pixel.

Apple Touch Events

Safari on iOS created the touch events, a series of 4 events that we can detect on any DOM element. Most of the other mobile browsers (excluding IE) support this specification.

The events available are:

  • touchstart
  • touchend
  • touchmove
  • touchcancel

All the events can be attached using addEventListener or through HTML DOM properties, such as ontouchstart. Every event receives through the first argument a touches collection. This collection includes each of the current available touches as a Touch object where we can get coordinates (such as pageX):

document.addEventListener("touchstart", function(event) {
        var touches = event.touches;
        var quantity = touches.length;
        var firstTouch = touches[0];
        var coordinates = {
x: firstTouch.pageX, 
y: firstTouch.pageY 
}, false);

Gesture API

Compatible only with Safari on iOS, we can use gesture events to detect two-fingers rotate and pinch gestures:

document.addEventListener("gesturechange", function(event) {
        var currentRotation = event.rotation;
        var currentScale = event.scale;
}, false);

W3C Touch Events

W3C has standardized Apple Touch Events with the additions of touchenter and touchleave for dragging purposes. Firefox and BlackBerry smartphones and tablets are using this spec.

The Gesture API is not included.

Microsoft Pointer Events

Microsoft is using another approach through Pointer events (also to be standardized in the W3C). Pointer events inherit from mouse events; therefore instead of receiving a collection of touches we receive one call per touch only with the information of the current point.

Pointer events include support for touch, mouse, and styles; the most useful available events are pointerdown, pointerup, pointercancel, pointermove, pointerover, pointerout. In IE10, these events are prefixed with MS; for example: mspointerup.

document.addEventListener("mspointerdown", function(event) {
        var coordinates = {
x: event.clientX, 
y: event.clientY
}, false);

Gesture API

Microsoft also supports a Gesture API for more complex touch interaction detection, including:

  • msgesturehold
  • msgesturetap
  • msgesturestart
  • msgestureend
  • msgesturechange
  • msinertiastart
Section 7

Offline Support

Most mobile browsers support offline access through the Application Cache API. This API allows us to define a package that the browser will install for future access.

Step 1: Define the Manifest File

<!DOCTYPE html>
<html manifest="offline.manifest">

Step 2: Define the offline.manifest


# This is a comment line

# We define first the files that need to be downloaded
# The HTML file is always included in the package


# If we want the app to access some resources on the web
# We can define specific URLs or a pattern, such as *

Step 3: Detect Events Client-side

Through the object window.applicationCache we can detect several events over the process, such as downloading, cached, noupdate, and updateready.

function() {
                alert("The package was installed");
, false);

How Application Cache Works

If the webapp was installed (cached event) then next time the user accesses it, it will always be loaded from the cached version, even if the user has aconnection.

If there is a connection available, the browser will download the manifest file and it will compare byte-by-byte with the stored version. If it is the same, the noupdate event will be fired; if the manifest has changed, then the whole package will be discarded from the cache and downloaded again from the server firing the updateready event.

It's important to understand that when an update is available, the user is still seeing the old version as it was loaded from the cache, so the next reload or access will use the updated resources.

Section 8

Client-side Storage

Whether we are online or offline we can store information on the user's device using some of the client-side storage APIs, including localStorage, Web SQL Storage, IndexedDB and FileSystem API.

Limits vary per platform, but usually localStorage gives us safely at least 5Mb per origin (protocol+domain+port combination). On some platforms such as iOS, we can overpass the 5Mb limit with the user's permission usually up to 50Mb.

Section 9

Native Webapp

With HTML5 we can create native webapps, also known as hybrid apps, and distribute them through Application Stores.

These platforms require packaging all the resources, and sometimes compiling and signing processes.

The most important platforms to create native webapps are:


Name Platforms Compatible Stores
WebWorks BlackBerry 5.x-7.x
BlackBerry PlayBook
BlackBerry 10
BlackBerry AppWorld
Windows 8 Store HTML5 apps Windows 8 Microsoft Windows Store
Nokia S40 webapps Nokia Series 40 Nokia Store
Symbian webapps Symbian Nokia Store
Mozilla Open Web Apps Firefox OS
Mozilla Marketplace
Chrome Packaged Apps Desktop
Chrome OS
Android (future)
Chrome Store
Apache Cordova / Adobe PhoneGap iOS
Windows Phone
Bada / Tizen
Apple AppStore
Google Play Store
BlackBerry AppWorld
Microsoft Windows Phone Store
Nokia Store

The native HTML5 webapp should be distributed through an application store for free or for a fee. To do that, we need to register as publishers in the stores and pay the publisher fee as defined in the next table:

store publisher fee url
Apple AppStore USD 99 per year developer.apple.com/ios/program
Google Play Store USD 25 play.google.com/apps/publish
Amazon AppStore for Android Free developer.amazon.com/apps/apps
BlackBerry AppWorld Free appworld.blackberry.com/isvportal
Windows 8 Store Varies appdev.microsoft.com/StorePortals
Windows Phone Store USD 99 per year dev.windowsphone.com
Nokia Store EUR 1 publish.nokia.com
Section 10

Mobile Browsers

These are the available mobile browsers by platform:

Platform Default Browser Other Browsers
iOS Safari (WebKit) Opera Mini, Google Chrome (Web View)
Android Android Browser (WebKit) Google Chrome (4.0+), Firefox, Opera Mini, Opera Mobile, Opera (WebKit), UC Browser, Dolphin
BlackBerry BlackBerry Browser (WebKit) Opera Mini (for old smartphones)
Windows Phone Internet Explorer Nokia Xpress (experimental)
Symbian Nokia Browser (WebKit) Opera Mobile, Opera Mini
Firefox OS Firefox  
Kindle Fire (Android) Amazon Silk  
Nokia S40 Nokia Xpress Browser Opera Mini
Other Jasmine, Dolfin,NetFront, UC Web, webOS Browser (now Iris)
Section 11


These are the available emulators and simulators per platforms (source: http://emulato.rs):

Platform Host Platforms Where to get it for free
iOS Mac Search for Xcode on Mac App Store
Android Windows, Linux, Mac http://developer.android.com/sdk
Windows Phone Windows 8 Pro Visual Studio 2012 Express for Windows Phone
Windows 8 Tablet Windows 8 Pro Visual Studio 2012 Express for Windows 8
BlackBerry 10 Windows, Linux, Mac http://developer.blackberry.com/devzone/ develop/simulator/
BlackBerry 6/7 Windows http://us.blackberry.com/sites/developers/ resources/simulators.html
Firefox OS Windows, Linux, Mac https://addons.mozilla.org/en-US/firefox/addon/firefox-os-simulator/
Nokia S40 Windows https://www.developer.nokia.com/Develop/Series_40/
Section 12

Remote Debugging

Support for remote debugging for HTML, CSS and JavaScript:

Browser Host Browser Connection Method
Safari for iOS Safari for Mac USB cable with the device
Google Chrome on Android Google Chrome Windows, Mac or Linux USB cable with the device and ADB tools (Android Debug Bridge)
Firefox on Android and Firefox OS Firefox Windows, Mac or Linux TCP via IP Address (same Wi-Fi network)
BlackBerry 7 and 10 Browser Any Webkit-based desktop browser TCP via IP Address (same Wi-Fi network)
Opera Mobile for Android or Symbian Opera for Windows, Mac or Linux TCP via IP Address (same Wi-Fi network)
Section 13


These APIs might not be available on all the browsers and platforms. Check http://mobilehtml5.org for compatibility table.


    function(position) {
        var lat = position.coords.latitude;
var lon = position.coords.longitude;
    function () {
          alert('Error locating your device');

Accelerometer, Magnetometer & Gyroscope

We can read current acceleration in 3 axes measured in m/s2 including gravity or excluding it on some devices only:

window.addEventListener("devicemotion", function(event) {
        var acceleration = event.accelerationIncludingGravity;
        // acceleration.x, acceleration.y, acceleration.z

}, false);

We can also read current device orientation as alpha (direction according to the compass), beta (angle of the tilt front-to-back) and gamma (angle of the tilt left-to-right). All angles are measured in degrees.

window.addEventListener("deviceorientation", function(event) {
        var alpha = event.alpha;
        var beta = event.beta;
        var gamma = event.gamma;
}, false);


var battery = navigator.mozBattery || navigator.webkitBattery;
var level = battery.level * 100;
var charging = battery.charging;
var chargingTimeFully = battery.chargingTime;
var dischargingTimeEmpty = battery.dischargingTime;

// Events available
battery.addEventListener("levelchange", handler, false);
battery.addEventListener("chargingchange", handler, false);
battery.addEventListener("chargingtimechange", handler, false);
battery.addEventListener("dischargingtimechange", handler, false);


// One time vibration for 0.5 seconds
// Vibration pattern (vibration/pause)
navigator.vibrate([500, 500, 1000, 600,100]);

Media capture

Using HTML forms to capture media:

<input type="file" accept="image/*" capture="camera"> 
<input type="file" accept="audio/*" capture="microphone"> 
<input type="file" accept="video/*" capture="camcorder">

Reading the camera as <video> input:

var video = document.querySelector("video");
var URL = window.URL || window.webkitURL;
var getUserMedia = navigator.getUserMedia ||
   navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
var video = document.getElementById("player");
if (getUserMedia) {
getUserMedia({audio:true, video:true},
Section 14

Useful Resources

HTML5 documentation: www.webplatform.org
Can I Use Compatibility Tables: www.caniuse.com
HTML5 Compatibility Tables: www.mobilehtml5.org
HTML5 Rocks for Mobile: www.html5rocks.com/mobile
HTML5 demos: www.html5demos.com
Emulators and Simulators: www.emulato.rs
HTML5 Test: www.html5test.com
Ringmark: www.rng.io
Media Queries test: www.mediaqueriestest.com


  • Featured
  • Latest
  • Popular
Getting Started With Docker
Teaches you typical Docker workflows, building images, creating Dockerfiles, and includes helpful commands to easily automate infrastructure and contain your distributed application.
10.2k 7,169
Getting Started With Real User Monitoring
Teaches you how to use new web standards—like W3C’s Beacon API—to see how your site is performing for actual users, letting you better understand how to improve overall user experience.
4,442 3,655
Core Java
Gives you an overview of key aspects of the Java language and references on the core library, commonly used tools, and new Java 8 features.
104k 263.9k
JavaFX 8
Gives you what you need to start using the powerful JavaFX 8 UI and graphics tool with code snippets and visual examples of shapes and controls.
6,786 8,934
Continuous Delivery With Jenkins Workflow
Provides an introduction to the Jenkins Workflow plugin, a tool that extends the popular CD application to manage even the most complex software pipelines and help you continuously deliver more efficiently.
8,663 9,673
Functional Programming in JavaScript
Explains functions, data types, and techniques to demonstrate the functional paradigm through the familiar JavaScript language.
12k 8,665
Java Caching
Explores the building blocks of JCache and other caching APIs, as well as multiple strategies for implementing temporary data storage in your application.
10.5k 10.5k
Getting Started With Microservices
Still re-deploying your entire application for one small update? Microservices deploy modular updates and increase the speed of application deployments.
13.7k 14.1k
Getting Started With MQTT
Explores the fundamentals of MQTT, including message types, QoS levels, and security.
6,068 7,092
Monitoring NGINX
Overcome dropped connections, server errors, and more by efficiently monitoring your NGINX web server.
4,874 3,800
Getting Started With Apache Tomcat
Learn Apache Tomcat, a pure Java open-source web server that implements the Java Servlet, JavaServer Pages, and Expression Language specifications.
8,845 7,314
IntelliJ IDEA Essentials
Helps Java developers navigate the various facets of this world-class IDE, with tips, tricks, shortcuts, and quick tutorials on editor basics, navigation, and more.
20.4k 91k
{{ card.title }}
{{card.downloads | formatCount }} {{card.views | formatCount }}

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}