HTML5 brought about a huge selection of new features and finally provided a logical way for a lot of developers to add video, audio and responsive images to their sites.

However, HTML5 introduced well over 30 new HTML tags some that have little documentation and a handful of fantastic new API's that make up a large part of the specification itself.

HTML5 API's - Web Design Cheshire

Interactive Elements

The Interactive Elements API is a huge bundle of smaller API's that make it up consisting of details on how to build menu's and toolbars, context menu's and toolbars alone.

The new ContextMenu API allows you to add additional items to the browser's default menu or, design a completely new menu. The example below is taken from the website:

<form name="npc">
     <label>Character name: <input name="char" type="text" contextmenu="namemenu" required></label>
     <menu type=context id=namemenu>
        <command label="Pick random name" onclick="document.forms.npc.elements.char.value = getRandomName()">
        <command label="Prefill other fields based on name" onclick="prefillFields(document.forms.npc.elements.char.value)">

This adds two items to the control's context menu (when the user right clicks on the text input). The items are "Pick random name" and "Prefill other fields based on name".

At present, Mozilla Firefox is the only browser to support this API.

The Toolbar API allows you to recreate the menu style effects in Windows Desktop applications. Developers use the API to create menu's (similar to the context menu, although that is event specific triggered) that can be triggered from a button, label, link, etc. This example is taken from the website:

<menu type="toolbar">
        <menu label="File">
            <button type="button" onclick="fnew()">New...</button>
            <button type="button" onclick="fopen()">Open...</button>
            <button type="button" onclick="fsave()">Save</button>
            <button type="button" onclick="fsaveas()">Save as...</button>
        <menu label="Edit">
            <button type="button" onclick="ecopy()">Copy</button>
            <button type="button" onclick="ecut()">Cut</button>
            <button type="button" onclick="epaste()">Paste</button>
        <menu label="Help">
            <li><a href="help.html">Help</a></li>
            <li><a href="about.html">About</a></li>

It is well-worth a thorough read through the API as it lists details on how to use the command and accessKey attributes to enhance the overall experience.


The postMessage API, allows for message sending between windows and iFrame elements.

// Get the iframe
var win = document.getElementById("iframe").contentWindow;
// When the user submit, post the message they typed to the frame
addEvent(document.querySelector('form'), 'submit', function (e) {
	if(e.preventDefault) {
	// otherwise set the returnValue property of the original event to false (IE)
	e.returnValue = false;

You can trial a live demo of the code above on HTML5 Demos: postMessage (cross domain).

HTML5 Storage

Whilst HTML5 storage articles are fairly common, it's good to touch on this topic to remind people of the fundamental concepts behind using localStorage. Storage is based on a key/value pair - typical of any storage.

Below is an example taken from HTML5 Demos: Storage to outline the inner-workings of using the getter/setter methods to store and retrieve your own data.

// I will run into detail on this below
// getStorage: The code they have provided allows users to access sessionStorage and localStorage. This code will verify if the browser supports that type of storage, and, if it does, it'll add to the relevant list the value in storage and the time it was added (run the demo)
function getStorage(type) {
	var storage = window[type + 'Storage'], 
	delta = 0, 
	li = document.createElement('li');
	// Browser doesn't support
	if(!window[type + 'Storage']) {
	// We have a value stored?
	if(storage.getItem('value')) {
		delta = ((new Date()).getTime() - (new Date()).setTime(storage.getItem('timestamp'))) / 1000;
		li.innerHTML = type + 'Storage: ' + storage.getItem('value') + ' (last updated: ' + delta + 's ago)';
	} else {
		li.innerHTML = type + 'Storage is empty';
	// Adds them to our element ID=previous
// Listen for when the user types a value
addEvent(document.querySelector('#local'), 'keyup', function () {
	localStorage.setItem('value', this.value);
	localStorage.setItem('timestamp', (new Date()).getTime());

You can trial a live demo of the code above on HTML5 Demos: Storage.

After running the example, entering some test storage data (it is automatically saved by the keyup event - you can change this to store on a specific button press, etc).

Content loaded from previous sessions:

  • sessionStorage: Testing (last updated: 3.361s ago)
  • localStorage: Test (last updated: 2.066s ago)

Element Dataset: data-* values

The dataset API, similar to HTML5 Storage, is a more well-known API that allows developers to get and set data-[name] attribute values on elements. This is ideal if you've got elements that you need to store relevant data for that you'll need to use for processing later on e.g. hiding rows of inactive accounts, or only showing accounts that are banned - you can use a data-status field and a selector to hide/show all with a data-status value of x, etc.

// Get the element
var element = document.getElementById("element");
// Get the ID
var ID =;
// Retrieves "data-retrieve-key"
var retrieveKey = element.dataset.retrieveKey;
// Sets the value to something else
element.dataset.retrieveKey = "New data value";
// This will produce an element:
// <div id="element" data-id="element" data-retrieve-key="New data value"></div>

In jQuery you can recreate this using the data method.

// Get the element
var element = $('#element');
// Get custom key
var retrieveKey ='retrieve-key');
// Set custom key'retrieve-key', 'New data value');

You can check a demo of code provided by HTML5 Demos: Data-*

Download Attribute

We discussed the download attribute in more detail here: How to use the HTML5 download attribute. It's a simple addition to HTML that is definitely one that makes life much easier for web applications that offer users the ability to download media such as images.

<a href="/images/some_long_file_name_123_123_0192.jpg" download="MyImage">Download image</a>

Page Visibility

The Page Visibility API lets your application know when a page becomes visible to the user. A developer can use this API to control the behaviour of the web site when it is not actually being viewed such as using pause states to minimise and cut back on AJAX polling tasks until the user puts the page back into focus.

// Define our variables
var timer = 0;
// We will use two times, poll quickly when the page is visible but when it isn't, poll much less
var PERIOD_VISIBLE = 1000;
function onLoad() {
    timer = setInterval(checkEmail, (document.hidden) ? PERIOD_NOT_VISIBLE : PERIOD_VISIBLE);
    if(document.addEventListener) {
		document.addEventListener("visibilitychange", visibilityChanged);
function visibilityChanged() {
    timer = setInterval(checkEmail, (document.hidden) ? PERIOD_NOT_VISIBLE : PERIOD_VISIBLE);
function checkEmail() { 
    // Check server for new emails

A great lengthly article on Using the PageVisibility API can be found on The Page Visibility API has become quite popular and some other articles worth a read for more details are:

If you use jQuery, you may wish to use the jQuery Visibility API that takes full advantage of the Page Visibility API. An example, condensed code is:

if($.support.pageVisibility) {
  // Page Visibility is natively supported in this browser
	'show': function() {
		console.log('The page gained visibility; the `show` event was triggered.');
	'hide': function() { 
		console.log('The page lost visibility; the `hide` event was triggered.');

Capturing Audio & Video

The getUserMedia API allows web applications access to a user's camera and microphone. If support, developers can access the devices camera to take a snapshot of themselves using the following code:

<!-- Use the camera -->
<input type="file" accept="image/*;capture=camera" />
<!-- Record a video or audio -->
<input type="file" accept="video/*;capture=camcorder" />
<input type="file" accept="audio/*;capture=microphone" />

Below is code that outlines how to verify the getUserMedia API is supported, and, if it is,use it to take a screenshot:

function hasGetUserMedia() {
	return !!(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
// Are we supported?
if(hasGetUserMedia()) {
	var video = document.querySelector('video');
    var canvas = document.querySelector('canvas');
    var ctx = canvas.getContext('2d');
    var localMediaStream = null;
    function snapshot() {
        if(localMediaStream) {
			ctx.drawImage(video, 0, 0);
            // "image/webp" works in Chrome 18. In other browsers, this will fall back to image/png.
           document.querySelector('img').src = canvas.toDataURL('image/webp');
    video.addEventListener('click', snapshot, false);
    // Not showing vendor prefixes or code that works cross-browser.
navigator.getUserMedia({video: true}, function(stream) { video.src = window.URL.createObjectURL(stream); localMediaStream = stream; }, onFailSoHard); } else { alert('getUserMedia() is not supported in your browser'); }

The example above was provided by We strongly suggest you head over there for a more in-depth look at all features of the getUserMedia API - Capturing Audio & Video in HTML5.

SEE ALSO: Handling Responsive Images with the Picture Attribute

Battery Status

The Battery API is a mobile-targeted API that provides developers insight into the device's battery level and device status. This API provides a similar scope of identification as the Page Visibility API, allowing developers to pause resource intensive operations if the device has low battery, etc.

// Get the battery!
var battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery;
// A few useful battery properties
console.warn("Battery charging: ", battery.charging); 
console.warn("Battery level: ", battery.level);
console.warn("Battery discharging time: ", battery.dischargingTime);
// Add a few event listeners
battery.addEventListener("chargingchange", function(e) {
  console.warn("Battery charge change: ", battery.charging);
}, false);

The code above was based off the demo listed on HTML5 Battery Status. If you use jQuery, you can check out the HTML5 Battery API Experiment on GitHub that expands on the API to provide an extended functionality to what is provided above.

Other Resources

Ignite your brand, utilise user-generated content no matter where you or your audience are ›