Maximiliano Firtman's articles, notes and learning experiences for devs-firt.dev

HTML5 Mobile Development

Cheat Sheet, Important Technologies, Tools and Frameworks

Maximiliano Firtman avatarby Maximiliano Firtman Twitter @firt About Newsletter

About 9 min reading time

Mobile HTML5 This cheat sheet covers the most important HTML5 mobile technologies and is intended to bring you up to speed in mobile HTML5 development.

Originally published at https://dzone.com/refcardz/html5-mobile-development.

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 Value
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

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:

<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">

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

CSS3

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";
}

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"
content="frequency=1440;polling-uri={xml-url}">

The XML will look like:

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

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.

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")
}

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

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 #

CACHE 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

CACHE:
styles/mystyles.css
scripts/mycode.js
images/myimages.png

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

NETWORK

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.

window.applicationCache.addEventListener("cached", 
  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.

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.

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)

HTML5 APIs #

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

Geolocation

navigator.geolocation.getCurrentPosition(
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);

Battery

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);

Vibration

// One time vibration for 0.5 seconds
navigator.vibrate(500);
// 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},
function(stream){
video.src=URL.createObjectURL(stream);
video.play();
});
}
Half typewriter, half computer

© Maximiliano Firtman (@firt)

firt.dev contains a collection of writings, thoughts, notes and learning experiences for web and mobile app developers authored by Maximiliano Firtman.

Contact me: hi@firt.dev Personal Website Buy Me A Coffee