• Feed RSS

HTML5 Unleashed: Tips, Tricks and Techniques

HTML5 Unleashed: Tips, Tricks and Techniques: "

Can we use HTML5 today? What can we do with it? Is it really going to kill Flash? You must have noticed a gradual increase in the frequency of these and similar questions being asked, debated and even answered. In my opinion, you must answer such fundamental questions yourself.

The whole purpose of this article is to help you get started with some basic guidelines and easy to follow code templates. If you are familiar with the basics and want to take things to the next level, you will also find several useful resources providing more tips, tricks and techniques.

HTML5 Features

Official Specification Document is the best place to look for HTML5 features, but you can also start with simple and easy to follow HTML5 Tag Reference at W3Schools. We will cover following features in this article:

  • Semantic Markup
  • Form Enhancements
  • Audio / Video
  • Canvas
  • ContentEditable
  • Drag and Drop
  • Persistent Data Storage

Check For Browser Support

Before you start experimenting with HTML5, you need to know level of support available for it in major web browsers. These useful resources will help you keep a track:

You can also detect HTML5 feature support on the fly using JavaScript (Guide to Detecting HTML5 Features With JavaScript). You must also check Modernizr: a really useful JavaScript library that detects native availability of HTML5/CSS3 features. If you prefer using MooTools, you can use MooModernizr (MooTools port of Modernizr).

You may also want to keep an eye on constantly changing “Browser Market Share” – this information will be helpful when you need to determine if any workarounds or fallbacks are necessary.

Note Changes

In addition to the new features, you should also take a note of following important changes:

  • Simple DOCTYPE
    HTML5 requires very simple and easy to remember DOCTYPE: <!DOCTYPE html>. It intentionally contain no version, so the DOCTYPE will remain usable for all future revisions of HTML.
  • Easy to Remember Attribute For Language
    You are not required to use xmlns or xml:lang attributes in the <html> tag. <html lang=”en”> will now do the trick with HTML5.
  • Easy to Remember Attribute For Character Set
    You can now define character encoding, using new “charset” attribute in the meta tag: <meta charset=”utf-8″ />
  • Trailing Slashes Not Required
    Void elements in HTML5 (e.g. the br, img and input  elements) don’t require a trailing slash.
  • Elements Thrown Away
    Following elements are not supported in HTML5: <acronym>, <applet>, <basefont>, <big>, <center>, <dir>, <font>, <frame>, <frameset>, <noframes>, <s>, <strike>, <tt>, <u> and <xmp>

Sample Code:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>HTML5 Document</title>
</head>
<body>

</body>
</html>

You can use HTML5 Validator to test your HTML5 documents.

Semantic Markup

Several new elements proposed in HTML5 are meant to only add more semantic markup, and will do nothing except provide a more meaningful alternative to <div>. These new elements include: <article>, <section>, <aside>, <hgroup>, <header>, <footer>, <nav>, <time>, <mark>, <figure>, and <figcaption>.

These elements are available in all modern browsers (Firefox 3+, Safari 3.1+, Chrome 2+, and Opera 9.6+), except for Internet Explorer. JavaScript offers an easy solution with “document.createElement(tagName)”; that you can use to create new HTML5 elements in IE. Instead of creating these elements yourself, you can also use HTML5 Enabling Script or IE Print Protector – these scripts will also help IE render HTML5 elements correctly in print.

You may also want to apply CSS reset to these new elements. Here are few CSS resets that you can use in your HTML5 based projects:

Sample Code: HTML5 Page Layout With IE Support.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>HTML5 Semantic Markup Demo: Cross Browser</title>
    <link rel="stylesheet" href="html5reset.css" type="text/css" />
    <link rel="stylesheet" href="html5semanticmarkup.css" type="text/css" />
    <!--[if lt IE 9]>
        <script src="html5.js"></script>
    <![endif]-->
</head>
<body>
    <header>
        <hgroup>
            <h1>Page Header</h1>
            <h2>Page Sub Heading</h2>
        </hgroup>
    </header>

    <nav>
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">Projects</a></li>
            <li><a href="#">Portfolio</a></li>
            <li><a href="#">Profile</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </nav>

    <article>
        <header>
            <h1>Article Heading</h1>
            <time datetime="2010-05-05" pubdate>May 5th, 2010</time>
        </header>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        <section>
            <header>
                <h1>Section Heading</h1>
            </header>
            <p>Ut sapien enim, porttitor id feugiat non, ultrices non odio.</p>
            <footer>
                <p>Section Footer: Pellentesque volutpat, leo nec auctor euismod</p>
            </footer>
        </section>
        <section>
            <header>
                <h1>Section Heading</h1>
            </header>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
            <figure>
                <img src="item-1.png" alt="Club">
                <img src="item-2.png" alt="Heart">
                <img src="item-3.png" alt="Spade">
                <img src="item-4.png" alt="Diamond">
                <figcaption>FigCaption: Club, Heart, Spade and Diamond</figcaption>
            </figure>
            <p>Ut sapien enim, porttitor id feugiat non, ultrices non odio</p>
            <footer>
                <p>Section Footer: Pellentesque volutpat, leo nec auctor euismod est.</p>
            </footer>
        </section>
        <footer>
            Article Footer
        </footer>
    </article>

    <aside>
        <header>
            <h1>Siderbar Heading</h1>
        </header>
        <p>Ut sapien enim, porttitor id feugiat non, ultrices non odio.</p>

    </aside>

    <footer>
        Page Footer
    </footer>

</body>
</html>

Note: Not a single “div” element, “id” or “class” attribute is used – Clean, Lean and more Meaningful Markup (View Demo). You should still be able to validate your document using HTML5 Validator.

Note: Our demo will not render correctly in IE6. This is only because I am using CSS child combinators to avoid use of additional classes. You can render HTML5 markup in IE6 like in any other browsers, using your own CSS.

Additional Resources

Form Enhancements

HTML5 provides several new attributes, input types and elements for web forms. As of today, only Opera provides decent support for HTML5 forms. You must therefore download Opera to see how most of the new features will work.

The good news is that even with very limited support, using some of these features may not be a bad idea. This is because new input types will degrade nicely to regular text fields. And remember you can always fallback on JavaScript based form controls that you use today (the trick is to detect for native support first and then use a fallback).

Sample Code: Showcasing some new features that you can test today.

<form>
    <fieldset>
        <legend>New Attributes</legend>
        <p>
            <label>Required:</label>
            <input type="text" name="html5requied" required="true">
            <small>Works in Opera & Chrome</small>
        </p>
        <p>
            <label>AutoFocus:</label>
            <input type="text" name="html5autofocus" autofocus="true">
            <small>Works in Opera, Chrome & Safari</small>
        </p>
        <p>
            <label>PlaceHolder:</label>
            <input type="text" name="html5placeholder" placeholder="This Will Show in WebKit">
            <small>Works in Chrome & Safari</small>
        </p>
        <p>
            <label>Input Pattern:</label>
            <input type="text" pattern="[0-9][A-Z]{3}" name="html5pattern" required title="Enter a digit followed by three uppercase letters"/>
            <small>Works in Opera & Chrome</small>
        </p>
        <p>
            <label>Multiple Files:</label>
            <input type="file" name="html5multiplefileupload" multiple>
            <small>Works in Chrome, Safari & Firefox</small>
        </p>
        <p>
            <label>List:</label>
            <input type="text" name="html5textwithdatalist" list="colors">
            <datalist id="colors">
                <option value="Red">
                <option value="Green">
                <option value="Blue">
            </datalist>
            <small>Works in Opera</small>
        </p>
    </fieldset>

    <fieldset>
        <legend>New Input Types</legend>
        <p>
            <label>Email:</label>
            <input type="email" name="html5email">
            <small>Works in Opera</small>
        </p>
        <p>
            <label>URL:</label>
            <input type="url" name="html5url">
            <small>Works in Opera</small>
        </p>
        <p>
            <label>Number:</label>
            <input type="number" name="html5number" min="1" max="10" step="1" value="1">
            <small>Works in Opera</small>
        </p>
        <p>
            <label>Range:</label>
            <input type="range" name="html5range" min="-100" max="100" value="0" step="10">
            <small>Works in Opera, Chrome & Safari</small>
        </p>
        <p>
            <label>Time:</label>
            <input type="time" step="900" name="html5time">
            <small>Works in Opera</small>
        </p>
        <p>
            <label>Date:</label>
            <input type="date" name="html5date">
            <small>Works in Opera</small>
        </p>
        <p>
            <label>Month:</label>
            <input type="month" name="html5month">
            <small>Works in Opera</small>
        </p>
        <p>
            <label>Week:</label>
            <input type="week" name="html5week">
            <small>Works in Opera</small>
        </p>
        <p>
            <label>DateTime:</label>
            <input type="datetime" name="html5datetime">
            <small>Works in Opera</small>
        </p>
    </fieldset>

    <div><button>Submit</button></div>
</form>

Most of the features showcased in our demo will work in Opera, but you will also need to use Chrome or Safari to see few remaining features in action (View Demo).

Learn More:

Tools & Resources:

Audio & Video Without Plugins

HTML5 specification in regards to audio and video is one of its most talked about feature. In addition to the obvious benefits of having native audio and video support, this debate is mainly focused on differences in audio / video formats preferred by browser vendors. If you are going to use HTML5 <audio> and <video>, it is important that you get yourself familiar with following audio/video codecs and know which browser will support what:

You should also keep an eye on Google’s VP8 video codec, which it may offer as open source to end the controversy. HTML5 offers a solution by allowing you to specify more than one source file (in different formats), so that user’s browser will play the file it understands. For Internet Explorer and older browsers you will need to fallback on current solutions.

When you first start experimenting with HTML5 audio / video,  you may want to note couple of things that may be helpful:

  • Your web server must support audio / video MIME types for the file formats that you intend to serve. You will specially need to check this if you are testing HTML5 audio/video on your local web server.
  • If you are using Safari to test HTML5 audio / video, you must install QuickTime player as well. Safari can not play anything without QuickTime.

Sample Code: Audio Markup (View Demo)

        <audio controls>
            <source src="demo-audio.ogg" />
            <source src="demo-audio.mp3" />
        </audio>

Sample Code: Video Markup (View Demo)

        <video width="320" height="240" controls preload="none" poster="videoframe.jpg">
            <source src="demo-video.mp4" type="video/mp4" />
            <source src="demo-video.ogv" type="video/ogg" />
        </video>

Although a big step from having to depend on third party plugins, the above examples are just a starting point. Since each browser provide its own look and feel for controls, you may want to change them to match your design . Following is a simple example of how to use DOM API to create your own custom controls.

Sample Code: Video With Custom Controls (View Demo)

        <video width="320" height="240" preload="none" poster="videoframe.jpg">
            <source src="demo-video.mp4" type="video/mp4" />
            <source src="demo-video.ogv" type="video/ogg" />
        </video>

        <script>
            var video = document.getElementsByTagName('video')[0];
            function toggleMute() {
                video.muted = !video.muted;
            }
        </script>
        <p>
            <a href="JavaScript:video.play();">Play</a> |
            <a href="JavaScript:video.pause();">Pause</a> |
            <a href="JavaScript:toggleMute();">Sound On/Off</a>
        </p>

You can still do a lot more with DOM API for audio and video. But you can take things to an entirely different level if you are willing to mix things a little bit. For example, you can place your video on HTML5 canvas element. This will allow you to read pixel data, manipulate or process frames from a video and do some awesome stuff (See for yourself: Blowing up HTML5 Video, Ambilight for HTML5 Video).

Learn More:

Cross Browser Solutions:

JavaScript Interfaces

Encoding/Conversion Tools:

2D Drawing With JavaScript

One of the most exciting feature of HTML5 is the <canvas> element – which can be used to draw graphics. Inserting a canvas element in your page is as simple as adding any other markup, but you will need to have some programming experience to create basic shapes, graphs, animations, games, image composition, etc.

Canvas is available in all modern browsers (Firefox 3, Safari 3.1, Chrome 2, and Opera 9.6), except for Internet Explorer. You can use ExplorerCanvas, a JavaScript solution to add this feature in Internet Explorer.

Sample Code: Command Based 2D Drawing on HTML5 Canvas (View Demo).

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>HTML5 Canvas Demo</title>
    <link rel="stylesheet" href="html5reset.css" type="text/css" />
    <link rel="stylesheet" href="html5simple.css" type="text/css" />
    <!--[if lt IE 9]>
        <script src="html5.js"></script>
        <script src="excanvas.js"></script>
    <![endif]-->
        <script type="text/javascript">
        function draw(){
            var canvas = document.getElementById('mycanvas');
            if (canvas.getContext){
                var ctx = canvas.getContext('2d');

                // Draw Rectangle
                ctx.fillStyle = "rgb(255,0,0)";
                ctx.fillRect (10, 10, 100, 100);

                // Draw Circle
                ctx.fillStyle = "rgb(0,255,0)";
                ctx.beginPath();
                ctx.arc(125,100,50,0,Math.PI*2,true);
                ctx.fill();
                ctx.closePath();

                // Draw Custom Shape With Lines
                ctx.fillStyle = "rgb(0,0,255)";
                ctx.beginPath();
                ctx.moveTo(125,100);
                ctx.lineTo(175,50);
                ctx.lineTo(225,150);
                ctx.fill();
                ctx.closePath();

                // Draw Image From External File
                var myImage = new Image();
                myImage.onload = function(){
                    ctx.drawImage(myImage, 220, 10);
                }
                myImage.src = "sample.jpg";

            }
        }
        </script>
        <style type="text/css">
            canvas {
                border: 5px solid #ccc;
                background: #000;
            }
        </style>
</head>
<body onload="draw();">
    <header>
        <h1>HTML5 Canvas Demo</h1>
    </header>

    <figure>
        <canvas id="mycanvas" width="300" height="200">Fallback content, in case the browser does not support Canvas.</canvas>
        <figcaption>Works in Firefox 3+, Safari 3.1+, Chrome 2+ and Opera 9.6+)</figcaption>
    </figure>
</body>
</html>

Learn More:

Tools & Resources:

Examples & Applications:

Making Content Editable

If you want to allow users to edit content some where in your page, all you need to do is set contenteditable attribute of the container element. You have probably seen it in action in web based WYSIWYG editors. This attribute is part of HTML5 specifications, and is supported by all major browsers (Internet Explorer 5.5+, Firefox 3+, Safari 3.1+, Chrome 2+, and Opera 9.6+).

Note that setting contenteditable=“true” will allow users to edit, delete and insert content, but it will not automatically provide any controls like you see in WYSIWYG editors to save changes or apply styles. You will need to use JavaScript to add these controls yourself.

Sample Code: Basic content editor with bold, italic and underline controls (View Demo).

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>HTML5 ContentEditable Demo</title>
    <link rel="stylesheet" href="html5reset.css" type="text/css" />
    <link rel="stylesheet" href="html5simple.css" type="text/css" />
    <!--[if lt IE 9]>
        <script src="html5.js"></script>
    <![endif]-->

    <script language="javascript">
    function editStyle(cmd) {
        document.execCommand(cmd, null, null);
    }
    </script>
</head>
<body onload="draw();">
    <header>
        <h1>HTML5 ContentEditable Demo</h1>
    </header>

    <div id="democontainer">
        <div id="editingcontrols">
            <a href="#" onclick="editStyle('bold');">[Bold]</a>
            <a href="#" onclick="editStyle('italic');">[Italic]</a>
            <a href="#" onclick="editStyle('underline');">[Underline]</a>
        </div>
        <div id="editor" contenteditable="true">
            <h2>HTML5 Standardized Content Editing</h2>
            <p>Thanks to Microsoft; HTML elements are editable since Internet Explorer 5.5....</p>
            <p>To edit just start typing. To change style, select text and click on links in the tools bar.</p>
        </div>
    </div>

</body>
</html>

Learn More:

Tools & Resources:

Drag and Drop

HTML5 “Drag and Drop” will take user interaction to a whole new level and will have major impact on how you design user interfaces. As of today Firefox 3.5+ provides best support for this feature, and other browsers are cautiously following with only partial support (Opera provides no support at all). Unfortunately due to differences in vendor implementation at this time, you will need to heavily rely on JavaScript and CSS to make it work cross browser.

Note:

  • Image and Hyperlink elements can be dragged by default. For all other elements, HTML5 introduced a new attribute “draggable”; which needs to be set in order to make the element draggable.
  • Following events are associated with Drag and Drop: dragstart, drag, dragenter, dragover, dragleave, drop and dragend. You will need to write function (event handlers) that will take care of what you need to do when these events are fired. You may attach event listeners to the elements and/or do event delegation to simplify your code.
  • Drag and Drop events also let you transfer data along with the dragged element, using getData and setData methods of event’s “dataTransfer” property.
  • You can perform drag and drop between different browser windows, and even other applications.

Sample Code: Drag and Drop images from one container to another (View Demo).

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>HTML5 Drag & Drop Demo</title>
    <link rel="stylesheet" href="html5reset.css" type="text/css" />
    <link rel="stylesheet" href="html5simple.css" type="text/css" />
    <!--[if lt IE 9]>
        <script src="html5.js"></script>
    <![endif]-->

    <script>
    function DragHandler(target, e) {
        e.dataTransfer.setData('Text', target.id);
    }

    function DropHandler(target, e) {
       var id = e.dataTransfer.getData('Text');
       target.appendChild(document.getElementById(id));
       e.preventDefault();
    }
    </script>
</head>
<body>
    <header>
        <h1>HTML5 Drag & Drop Demo</h1>
    </header>
<div id="dndcontainer">
    <div ondrop="DropHandler(this, event)" ondragenter="return false" ondragover="return false" class="dndbox">
        <img src="item-1.png" id="club" ondragstart="DragHandler(this, event)" width="75" height="75" border="0" alt="" />
        <img src="item-2.png" id="heart" ondragstart="DragHandler(this, event)" width="75" height="75" border="0" alt="" />
        <img src="item-3.png" id="spade" ondragstart="DragHandler(this, event)" width="75" height="75" border="0" alt="" />
        <img src="item-4.png" id="diamond" ondragstart="DragHandler(this, event)" width="75" height="75" border="0" alt="" />
    </div>

    <div ondrop="DropHandler(this, event)" ondragenter="return false" ondragover="return false" class="dndbox"></div>

    <div id="demonotes">Drag and drop images from one container to another. Works in all major browsers except Opera.</div>

</div>

</body>
</html>

Learn More:

JavaScript Solutions

Persistent Data Storage

Web Storage specifications provides two new attributes for persistent data storage similar to HTTP session cookies. These are “sessionStorage” and “localStorage”.

  • sessionStorage is used to save data during lifetime of top-level browsing context (i.e., as long as its browser tab or window remains open).
  • localStorage is used to store data for longer period of time, over multiple pages and browser sessions (i.e., will last even when you restart your web browser and / or  computer).

Both local and session storage features are supported in following web browsers: IE8+, Firefox 3.5+, Safari 4.0+, Chrome  2.0+ and Opera 10.5+.

Sample Code: Using localStorage to create a page counter (View Demo).

        <p>You Have Viewed This Page <b>
        <script>
            if (!localStorage.pageCounter)
                localStorage.setItem('pageCounter',0);
            localStorage.setItem('pageCounter',parseInt(localStorage.pageCounter)+1);
            document.write(localStorage.pageCounter);
        </script>
        </b> Time(s).</p>

        <p><input value="Clear localStorage" type="button" onClick="localStorage.clear();location.reload(true);" />
        <input value="Reload Page" type="button" onClick="location.reload(true);" /></p>

You can also test sessionStorage by replacing all instances of “localStorage” with “sessionStorage” in the above code. Your counter will now work as long as its browser tab or window remains open. If you restart your browser, counter will start from the beginning (View Demo).

Learn More:

JavaScript Solutions:

There’s More

In addition to things already discussed, there are many more features and related technologies that you may want to keep track of. Here is brief list of resources to help you out:

Offline Web Applications

HTML5 specifications also define how to enable users to continue interacting with Web applications and documents, even when their network connection is down. This feature is currently supported by Firefox 3.5+, Chrome 4.0+, Safari 4.0+ and Mobile Safari 3.1+.

You can create your offline application by providing a manifest file that defines which files needs caching and which files needs to be replaced by fallbacks in offline mode. When a user visits this page, supporting web browser will fetch a copy of the manifest. It will download and cache all the resources it mentions, and if the manifest has changed since user’s previous visit, it will download and cache all the resources again.

Cross Document Messaging

New specification also provide “postMessage” method that we can use to send information from pages on different domains to each other. This feature is available in all modern browsers (IE8+, Firefox3+, Safari 4+, Chrome 2+ and Safari 9.6+).

Access DOM Elements By Class Name

One of the most common things that we do in JavaScript is select DOM elements and do something dynamically. Most of us now use “getElementById” method to do this in pure JavaScript. HTML5 specifications have added “getElementsByClassName” method, that will provide major boost to performance of our scripts when trying to access elements by class name. This feature is available in all major browsers (Firefox3+, Safari 3.2+, Chrome 2+ and Safari 9.6+) except Internet Explorer.

More Features

Links to Official Specifications:

Related Technologies

Links to Official Specifications:

Additional Resources

If you are still craving for more information, you should checkout these resources.

Essential Bookmarks
  • HTML5 Draft
    Draft Proposal by WHATWG
  • The WHATWG Blog
    Official blog of the WHATWG – group responsible for HTML5 specification.
  • WHATWG Wiki
    Place for WHATWG contributors to post and compile their own proposals and ideas regarding WHATWG specifications.
  • Dive Into HTML5
    Mark Pilgrim elaborates on a hand-picked selection of features from the HTML5 specification. This is a work in progress that will finally be published on paper by O’Reilly.
  • HTML5 Validator
  • Oline tool for testing your HTML5 documents.
  • Planet HTML5
  • HTML5 Revision Tracker
    Provides an online interface for selecting and comparing revisions of the specifications.
  • HTML5 Doctor
    Online community focused on helping you implement HTML5 today.
Demos / Showcases
Cheat Sheets
Frameworks
  • Less
    An HTML5 powered CSS framework for building flexible multi column website layouts for varying screen widths.
  • 52Framework
    A web development framework that is aimed at enabling you to implement HTML5 and CSS3 in your projects today.
  • SproutCore
    A JavaScript HTML5 application framework developed as a Ruby gem.
  • Frame
    Frame is a modular CSS framework that supports: Layout, Typography, Forms, Code, Table, Reset, and Print styling. It is HTML5 compatible, and provides default styles and support for HTML5 elements.
General Articles & Tutorials

Demos & Download

You can download all demos in a single ZIP file. Note: Audio / video files are not included in the download.

View Demo Now Download Files

I hope you have enjoyed this post and found it useful. Please feel free to suggest any addition, correction or updates in your comments.

Similar Posts:

You can also stay updated by following us on Twitter, becoming a fan on Facebook or by subscribing to our FriendFeed.

"