An introduction to HTML5 / (& CSS3)

  • Use the arrow keys to navigate through the slides. Use the Up / Down / Left and Right keys.
  • Press ESC to enter the slide overview.

HTML 4 / XHTML 1


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <meta http-equiv="content-type" 
        content="text/html; charset=utf-8" />
        <title>Title</title>
        <link rel="stylesheet" href="example.css"
                 type="text/css">
        <script type="text/javascript" src="example.js">
                </script>
    </head>
    <body>
        <p>Hello World</p>
    </body>
</html>
                    

HTML5 what changed?


<!DOCTYPE html>
<html lang=en>
    <head>
        <meta charset=UTF-8>
        <title>Title</title>
        <link rel=stylesheet href=example.css>
        <script src=example.js></script>
    </head>
    <body>
        <p>Hello World</p>
    </body>
</html>
                    

shorter doctype

no more namespace

shorter charset meta tag

no more type parameter

attribute quotes are optional

title must be in head (not new but important)

What else is new (advantages)

  • Semantic tags + microdata = better SEO
  • Native > javascript download on each page
  • Standardization (of things you already used before but which were not standards / attributes values you often used are now semantic tags)
  • UTF-8 + URI = IRI
  • no need to have <html> <head> and or <body> tags (browser adds them autonatically / try it out view source VS inspect element)

<!DOCTYPE html>
<meta charset="UTF-8">
<title>Title</title>
<p>Hello World</p>
                        

For a complete list of differences from HTML4 check the w3c page.


Are you ready for HTML5?

Self closing tags

Of course this is valid:


<br>
                    

But the XML style from XHTML is still valid too:


<br />
                    

Check out the w3c syntax guide: http://www.w3.org/TR/html5/syntax.html

HTML5 is not XML but closing tags are still valid.

If you want to check the validity of self closing tags with a space and slash at the end in HTML5 use the w3c validator: http://validator.w3.org/check


    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>HTML5 self closing tags</title>
            <base href="http://www.example.com/" target="_blank" />
            <link rel="stylesheet" href="#" />
            <meta name="author" content="chris.lu" />
        </head>
        <body>
            <map name="foo"><area /></map>
            <br />
            <table><colgroup><col /></colgroup><tr><th></th></tr></table>
            <command />
            <embed />
            <hr />
            <img src="#" alt="#" />
            <input />
            <keygen />
            <object data="#"><param name="#" value="#" /></object>
            <audio><source src="#" /></audio>
            <video><track src="#" /></video>
            <wbr />
        </body>
    </html>
                    

Outlining

  • every document has an outline
  • outlining is now standardized (defined in HTML5)
  • influenced by h1-h6, hgroup, section, article, aside, nav (but not header and footer)
  • outlining = (semantic) structure

More to read:
smashingmagazine article
html5doctor article
mozilla developer zone article

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>html5 outlining</title>
    </head>
    <body>
        <header>
            <hgroup>
                <h1>the content of h1</h1>
                <h2>the content of h2</h2>
            </hgroup>
            <nav>
                <ul>
                    <li>
                        <a href="#">first link</a>
                        <a href="#">second link</a>
                    </li>
                </ul>
            </nav>
        </header>
        <aside>
            <p>some aside content</p>
        </aside>
        <section>
            <p>section content</p>
            <article>
                <header>
                    <p>first article header</p>
                </header>
                <p>first article</p>
                <footer>
                    <p>first article footer</p>
                </footer>
            </article>
            <article>
                <p>second article</p>
            </article>
        </section>
        <footer>
            <p>some footer content</p>
        </footer>
    </body>
</html>
                    
test this code in an online outliner:
http://hoyois.github.com/html5outliner/
or
http://gsnedders.html5.org/outliner/

New (semantic) tags

http://dev.w3.org/html5/html4-differences/#new-elements

<section>

  • it's a grouping tag (thematic group)
  • add microdata to the tag to enhance semantic value
  • use only if hgroup, article, nav, aside, footer and header don't apply
  • don't use if it's only to apply a style, use div

<section id="news">
    The articles
    <section id="comments">
        The comments
    </section>
</section>
                    

<article>

  • use for posts / articles even in news list where only introduction is displayed
  • for comments you can nest article tags inside main article tag

<article>My Article</article>
                    

<aside>

  • use it to display related content or part of the main document

<section id="news">
    The news
</section>
<aside>
    A blogroll
</aside>
                    

<hgroup>

  • used to group more then one h(1-6) tag
  • the outliner will only display the h(1-6) with highest rank inside of hgroup

<hgroup>
     <h1>Foo</h1>
     <h2>Bar</h2>
</hgroup>
                    

<header>

  • group header data of a section or page
  • multiple header tags in one document are valid, one per article for example

<header>
    The page header
</header>
<article>
     <header>Article header</header>
</article>
                    

<footer>

  • most of the time last element of a page or section, but there can be another element between footer and the end
  • can be on top of the page or section tag if it's content is something that normally would be at the end of a content area, but for some purpose you prefer to display those informations on top, like a comments counter or informations about the author

<article>
     <footer>Article footer</footer>
</article>
<footer>
    The page footer
</footer>
                    

<nav>

  • around navigation elements of a page

<nav>
    <ul>
        <li>Menu item</li>
    </ul>
</nav>
                    

<figure> <figcaption>

  • can be around images, code or even videos
  • useful in combination with figcaption, to add a caption under the content
HTML5 badges (caption)

<figure>
    <img src="images/html5_badges.png" />
    <figcaption>HTML5 badges (caption)</figcaption>
</figure>
                    

<video>

  • video embedding without the use of a plugin
  • as fallback i recommend using a flash player (the video tag may contain an object tag which may contain an embed tag)

<video controls="controls" preload="auto" width="640" height="360">
    <source src="../video_track/bunny.webm" type="video/webm" />
    <source src="../video_track/bunny.mp4" type="video/mp4" />
    <object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'>
        <param name='movie'           value='player.swf'>
        <param name='allowfullscreen' value='true'>
        <param name='flashvars'       value='file=../video_track/bunny.mp4'>
        <embed src='player.swf'
                allowscriptaccess='always'
                allowfullscreen='true'
                flashvars="file=../video_track/bunny.mp4"
        />
    </object>
</video>
                    

<audio>

  • similar to video tag but (you guessed it) for audio files
  • audio streaming is (not yet) possible using the audio tag
  • multiple sounds at once using the tag is tricky, read this: cut the rope makers experience

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>HTML5 audio</title>
    </head>
    <body>
        <audio id="example" controls="controls" preload="auto">
            <source src="song.ogg" type="audio/ogg" />
            <source src="example.mp3" type="audio/mpeg" />
        </audio>
    </body>
</html>
                        
You might wonder, why in some tutorials you find an attribute autobuffer instead of preload. HTML5 replaced autobuffer (which had no value) by preload (which can have as values auto, metadata and none).

Codecs

Video codecs:

  • safari, chrome and IE: h.264
  • chrome, opera and firefox: ogg (Ogg Theora) and webm

Audio codecs:

  • safari, chrome and IE: mp3
  • chrome, opera and firefox: ogg (Ogg Vorbis)

source: caniuse.com

I you want to know why codecs are not part of the w3c standard anymore read about it on wikipedia and Ian Hickson's response on the whatwg mailinglist.

There is even a proposal for DRM in the works, something the industry wants to have but lots of users and perhaps some browser vendors don't want.

<track>

To learn more about webVTT, check the video on next page: http://www.youtube.com/watch?v=RoYvr-KXvLs

<embed> / (<object>)

  • You may already have used <embed> but it was never a standard, now it is
  • <embed> is only for plugin resources
  • <object> can be replacement for <img>, <embed>, <iframe>
  • before HTML5 IE supported <object> but firefox supported <embed>

<mark>

  • mark text in a context where you must increase visibility of text, that initially was not part of the document
  • example: in original article nothing is marked, but because the user came through search engine result page link, query words get marked

<progress>

  • progress bar to display progress of some action
  • a progress bar styling guide

demo:

Progress:


<progress value="22" max="100"></progress>
                    

There is a very good article about progress bar styling on css-tricks.

<meter>

  • display measurement of some action

demo:

Meter:


<meter value=55 min=0 max=100 low=30 high=70 optimum=80></meter>
                    
If the optimum is below min the meter color will be red, between min and max yellow and green above max. The colors will be in reverse order if the optimum is below min, min green, middle yellow and max green. If the optimum is between min and max the color is green else yellow.definition of optimum

If the meter belongs to a form but is placed outside of the form tags you can add the forms ID using the form attribute of meter, here is an example.

<time>

  • machine readable datetime attribute

    <article>
        <time datetime="YYYY-MM-DDThh:mm:ssTZD">
        <time datetime="2012-04-17" pubdate="pubdate">17.4.2012</time>
    </article>
                        

A good article describing how to use the time tag can be found on Bruce Lawson's blog

Some time ago the time tag was dropped, but then after protest of web developers was put back in.

The pubdate attribute is a boolean attribute. If specified, it indicates that the date and time given by the element is the publication date and time of the nearest ancestor article element, or, if the element has no ancestor article element, of the document as a whole. But it's not sure if the pubdate attribute will stay.

<ruby> / <rt> / <rp>

  • Will pass on this one as it is mainly useful for Asian languages

<bdi>

  • a span of text in which the direction is different compared to the default direction of the document

<wbr>

  • brother of br tag, but it only indicates that a br could be useful but does not enforce it
  • line break opportunity if text is too large to be in one line

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>wbr</title>
    </head>
    <body>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus id eleifend odio. Sed eget fermentum nisi. Donec posuere, nulla eget lobortis mattis, <wbr>(the &lt;wbr&gt; is here) quam dolor commodo dolor, ac hendrerit mi orci ut mauris. Donec sed lectus dui, vel gravida urna. Mauris vulputate nulla at est tincidunt a euismod leo commodo. Pellentesque pretium sapien pellentesque dui volutpat dictum. </p>
        <p>Llllooorrreeeemmmm<wbr>(&lt;wbr&gt;)iiiiippppppsssssuuuuummmmmm</p>
        <p>Llllooorrreeeemmmmmmiiiiiiiippppppsssssuuuuuuummmmmmm</p>
    </body>
</html>
                    

<canvas>

  • Another nice use case for canvas is displaying pdf documents by reading the pdf using pdf.js from mozilla and then using the canvas element to display it.
  • Examples of a games done with canvas are angry birds html5 and cut the rope html5.
when setting the size of a canvas area use the canvas tag width and height attributes, else image gets scaled to fir size defined by css

Basic example (Code):


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>html5 line canvas</title>
    <script>

        function initialize() {

            var canvas = document.getElementById('example');

            if (canvas.getContext) {

                var context = canvas.getContext('2d');

                fillRectangle(context);
                drawLine(context);

            }

        }

        function drawLine(context) {

            context.moveTo(100, 150);
            context.lineTo(250, 50);
            context.stroke();

        }

        function fillRectangle(context) {

            var gradient = context.createLinearGradient(0, 0, 0, 100);
            gradient.addColorStop(0, "#ff005a");
            gradient.addColorStop(1, "#ff985a");

            context.fillStyle = gradient;
            context.fillRect(50, 50, 150, 150);

        }

    </script>
    <style>
        canvas { 
            border: 1px solid blue;
        }
    </style>
</head>
<body onLoad="initialize();">
    <canvas id="example" width="500" height="300">Your browser does not support canvas ... go away!</canvas>
</body>
</html>
                        

Basic example (Result):

Your browser does not support canvas ... go away!

3D <canvas> WebGL

<command> / <menu>

  • A menu of commands for keyboard shortcuts or other javascript functions by using attributes like the onclick attribute

<menu type="toolbar">
    <command type="radio" radiogroup="alignment" checked="checked" label="Left" icon="icons/left.png" onclick="alert('left')">
    <command type="radio" radiogroup="alignment" label="Right" icon="icons/right.png" onclick="alert('right')">
    <hr>
    <command type="command" disabled label="Publish" icon="icons/disabled.png" onclick="alert('disabled')">
</menu>
                    

No browser has implemented this tag yet

<details> / <summary>

  • a widget to show / hide additional informations

<details>
    <summary>summary</summary>
    <p>Additional Data.</p>
</details>
                    
summary

Additional Data.

<datalist>

  • a list of options to add suggestions to an input field

<form>
    <input list="browsers">
    <datalist id="browsers">
        <option value="Chrome">
        <option value="Firefox">
        <option value="Safari">
        <option value="Internet Explorer">
        <option value="Opera">
    </datalist>
</form>
                    

<keygen>

<output>

  • form field for output

<dialog>

  • i wanted to mention this tag even if it got removed from the HTML5 specification because i think it was a great tag that would enhance the semantic meaning of a document as much as article does
  • the goal of this tag was to delimiter a comments section or a discussion / conversation section of a document
  • the html5docotor dialog article
  • (a developer from) Microsoft asked for this tag to be removed because they wouldn't have time to implement it

<div>

I know this one is not new, but with all the new semantic tags, you could wonder if there is still use for div and / or span.

Yes there is, use divs every time there is no tag with a semantic value that could replace it, or for content where you don' want to add semantic value because you just wont to be able to style it's content using CSS.

<address>

Was already available in HTML4.01 but there the address always referred to the document owner, in HTML5 address can be placed in an article and then represents the address of the article author.

Should i use the new tags today?

  • Most of them can be used now, some of them like video, audio and canvas tag should fallback to other technologies if not supported
  • Therefore you will probably need a feature detection like modernizr and polyfills to emulate the native feature in older browsers if modernizr tells you that the feature is not supported

    <!--[if lt IE 9]>
    <script src="//example.com/html5shiv-printshiv.js"></script>
    <![endif]-->
                        
Did you notice the double slash in the URI, this is valid, advantage of omitting the protocol (http: / https:), is that the browser will choose which to use depending on the protocol used by your page

data attribute

In HTML5 users can create custom attributes that will be valid, the only rule is that the attribute must be prefixed with data-, for example data-foo="bar".

it's recommended that you use a specific prefix after the data prefix for your app to avoid conflicts with other libraries you use that also use the data attribute but may not have an own prefix

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>html5 data attribute</title>
        <script>
            function initialize() {

                var example = document.querySelector('#example');

                // Add new data attributes via JS.
                example.dataset.myprefixFoo = 'bar';
                //example.setAttribute('data-myprefix-foo', 'bar');

                for (var key in example.dataset) {
                        console.log(key, ': ', example.dataset[key]);
                }

            }
        </script>
    </head>
    <body onload="initialize();">
        <p id="example" data-myprefix-hello="world">Example</p>
    </body>
</html>
                        

async attribute

A useful new attribute for script tags is the async attribute. It ensures you scripts get loaded asynchronously and don't block you page rendering. Async is useful for all javascript files that have code that you page needs at rendering time, but only later to progressively enhance your page.


<script src="example.js" async></script>
                    

The context menu attribute

The w3c HTML5 working draft specifies a new context menu attribute:

It allows you to add own entries in the context menu that appears when a user right clicks on an element

Right Click ME!


<!DOCTYPE html>
<meta charset="UTF-8">
<title>Context Menu</title>
<p contextmenu=examplemenu>Right Click ME!</p>
<menu type=context id=examplemenu>
    <command label="FOO" onclick="alert('FOO ACTION');">
    <command label="BAR" onclick="alert('BAR ACTION');)">
</menu>
                    

(As of today, works only in latest Firefox)

new input field types

  • tel
  • search
  • url
  • email
  • datetime
  • date
  • month
  • week
  • time
  • datetime-local
  • number
  • range
  • color

An howto for using yepnope and modernizr to detect the new native form input types or use a fallback can be found at css-tricks.com


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>html5 form input types</title>
    </head>
    <body>
        <form>
            <ul>
                <li><input type="tel" placeholder="tel" required="required"></li>
                <li><input type="search" placeholder="search" autofocus="autofocus"></li>
                <li><input type="url" placeholder="url"></li>
                <li><input type="email" placeholder="email"></li>
                <li><input type="datetime" placeholder="datetime"></li>
                <li><input type="date" placeholder="date"></li>
                <li><input type="month" placeholder="month"></li>
                <li><input type="week" placeholder="week"></li>
                <li><input type="time" placeholder="time"></li>
                <li><input type="datetime-local" placeholder="datetime-local"></li>
                <li><input type="number" placeholder="number"></li>
                <li><input type="range" placeholder="range"></li>
                <li><input type="color" placeholder="color" required></li>
                <li><input type="text" placeholder="pattern attribute" id="part" name="part" required pattern="[A-Z]{3}[0-9]{4}" title="Part numbers consist of 3 uppercase letters followed by 4 digits." /></li>
                <li><input type="submit" value="go4it"></li>
            </ul>
        </form>
    </body>
</html>
                        

html speech input field type

Side note not related to html5: Since google chrome 11, there is also a new input field attribute x-webkit-speech (not a standard from w3c and therefore not part of html5 / for chrome only)

google did submit a proposal for this to the w3c, speech input draft


<input type="text" x-webkit-speech />
                    

placeholder attribute

There is a new attribute called the placeholder attribute for forms input fields. It will create a semi transparent text inside input fields indented to eventually replace the label.


<input type="text" placeholder="placeholder text" />
                    

autofocus attribute

Use the autofocus attribute as attribute of the input field of your form if you want that field to be selected open opening the page.


<input type="text" autofocus />
<input type="text" autofocus="autofocus" />
                    

required attribute

Form fields can now have the attribute required, browsers like chrome will show a tooltip message near the field if the user tries to submit the form but the field is still empty and will prevent the submit event until the required field is not empty anymore.


<input type="text" required />
<input type="text" required="required" />
                    

pattern attribute

Using the pattern attribute you can define a regular expression that your field content is validated against. You should also use the title attribute and explain what you expect from the user.


<input type="text" placeholder="pattern attribute" id="part" name="part" required pattern="[A-Z]{3}[0-9]{4}" title="Part numbers consist of 3 uppercase letters followed by 4 digits." />
                    
If the input does not match the pattern, the CSS selector "invalid" will be added to the field and you can use it to style the field differently:

:invalid {
  border: 1px solid red;
}
                    

multiple attribute

To upload multiple files you can add the new multiple attribute to the file input tag. The other can now select multiple files and then click the upload button. You have to adapt your side side scripts to let them accept multiple file uploads and maybe should add some rules to avoid users spamming you with hundreds of file uploads.


<input type="file" multiple>
OR
<input type="file" multiple="multiple">
                    

should i use the new attributes and types now?

Why not? Add the new types and attributes to your form, anyway they degrade gracefully:

some browser will already support them and increase the usability of your forms, other browser won't support them, therefore you probably still want to add a javascript library with ui form widgets.

You can use modernizr to check if the browser supports them nativly or if you have to use the javascript fallback libraries like jQuery UI or dojo toolkit form widgets

link types

HTML5 defines some types of links using the rel attribute. One of the new values is prefetch with tells the browser that it can prefetch that link because it is likely this resource next.

Or the values prev and next which are useful for pagination.

Nofollow tells search engines that the link should not influence link targets rating (its useful to avoid hackers to spam your comments sections with posts full of links if you apply automatically nofollow to all links that are in comments).

The bookmark link type could be very usefull too, it specifies a permalink for the parent content. In combination with url shorteners like goo.gl and the rel="canonical" you could make permalinks that are usefull for the visitor as well as search engines. Canonical is not part of the HTML5 specification but it will not make your html5 page invalid, because the HTML5 specification says that values of the rel attribute that are unrecognized by the browser will be treated as normal links.

Here is a list and description of all rel values available in html5.

Microdata

Microdata are machine-readable labels that can enhance the semantic value of your documents for crawlers like google bot.

the w3c microdata specification.

A definition of structures for microdata from schema.org.

Microdata = SEO ?

I think so

Google has a very useful page about microdata, at the end of the page are examples of microdata that google recognizes like people or reviews. Go for example to the page reviews and there you will find examples howto use microdata to ensure google uses your data to create rich snippets that will enhance the search results of your site in google results pages.

You can test your page to check if google recognizes your microdata.

Look at the microdata example file, to see an example of a document containing a blog post and comments (source: w3c HTML5 specification).


<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="UTF-8">

        <title>html5 microdata</title>

    </head>

    <body>

        <article itemscope itemtype="http://schema.org/BlogPosting">

            <header>

                <h1 itemprop="headline">The Very First Rule of Life</h1>

                <p><time itemprop="datePublished" datetime="2009-10-09">3 days ago</time></p>

                <link itemprop="url" href="?comments=0">

            </header>

            <p>If there's a microphone anywhere near you, assume it's hot and

            sending whatever you're saying to the world. Seriously.</p>

            <p>...</p>

            <section>

                <h1>Comments</h1>

                <article itemprop="comment" itemscope itemtype="http://schema.org/UserComments" id="c1">

                    <link itemprop="url" href="#c1">

                    <footer>

                        <p>Posted by: <span itemprop="creator" itemscope itemtype="http://schema.org/Person">

                        <span itemprop="name">George Washington</span>

                        </span></p>

                        <p><time itemprop="commentTime" datetime="2009-10-10">15 minutes ago</time></p>

                    </footer>

                    <p>Yeah! Especially when talking about your lobbyist friends!</p>

                </article>

                <article itemprop="comment" itemscope itemtype="http://schema.org/UserComments" id="c2">

                    <link itemprop="url" href="#c2">

                    <footer>

                        <p>Posted by: <span itemprop="creator" itemscope itemtype="http://schema.org/Person">

                        <span itemprop="name">George Hammond</span>

                        </span></p>

                        <p><time itemprop="commentTime" datetime="2009-10-10">5 minutes ago</time></p>

                    </footer>

                    <p>Hey, you have the same first name as me.</p>

                </article>

            </section>

        </article>

    </body>

</html>
                        

absent tags and attributes

official list of absent tags and attributes from w3c

DOM4

DOM4 is not part of HTML5 but it will probably be part of modern web development as well as CSS3 which also isn't part of HTML5.

To learn more about DOM4 red the w3c editors draft.

One of the cool things DOM4 will offer are DOM Mutation Observers, a good article can be found on html5rocks.com.

audio API

An API for playing audio which can be used with the new audio tag.


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>html5 audio api</title>
        <script>
            function initialze() {
                console.log(document.getElementByID('example').duration);
                console.log(document.getElementByID('example').currentTime);
            }
        </script>
    </head>
    <body>
        <audio id="example" controls="controls" preload="auto">
            <source src="song.ogg" type="audio/ogg" />
            <source src="example.mp3" type="audio/mpeg" />
        </audio>  
        <div>  
            <button onclick="document.getElementById('example').play()">Play the Audio</button>  
            <button onclick="document.getElementById('example').pause()">Pause the Audio</button>  
            <button onclick="document.getElementById('example').volume+=0.1">Increase Volume</button>  
            <button onclick="document.getElementById('example').volume-=0.1">Decrease Volume</button>  
        </div>
    </body>
</html>
                        

A very nice audio library can be found on github. Audio.js is a javascript library which fallbacks to flash in older browsers that don't have the HTML5 audio capabilities.

video API

We have already seen the video tag, the track tag and the webVTT format for subtitles but there is even more. With the native browser API, you can choose not to use the native controls but build your own. Or make your script interact with the videos.

drag and drop API

The html5 drag and drop API will allow you to make items on your website draggable. Combined with the new file API you can even do drag and drop file uploads.

Two good articles that will help you get started with the drag and drop API by html5doctor and the html5rocks article.

try this drag and drop api example

history API (hashchange)

API that exposes the history and allows pages to add to it to prevent breaking the back button.

This new API is especially useful, if for example you use Ajax to retrieve a list of news and the user changes the filters and then he bookmarks the page. When he comes back, everything is reset and he sees the default news list again. But if you change the URI using the history API while he changes the filter options to save their state in the url and he then bookmarks the page, every time he comes back the filters will be set to the values he had selected when making the bookmark.

An impressive example of the history API, is github, check out how github only reloads the content area of the page and changes the url without reloading the whole page. jQuery Mobile also uses the history API, jQuery Mobile loads new pages using Ajax, adds those pages to the DOM and then changes the url.

As like other html5 APIs there is a javascript library polyfill for history, named history.js, it also supports older browser's by using the hash as fallback method

try this history api example

visibility API

This API sends out notifications if the current browser tab changes it's visibility, you can catch events like prerendering, visible or hidden status of your page.

Page visibility is still work in progress and it looks like it got implemented slightly differently by the browsers that support it (chrome, safari, opera and firefox, IE 10 will support it too). Therefore it might be a good idea to use a wrapper library like visibility.js that can be found on github.

The whole working draft about page visibility at w3.org

A nice page visibility example

geolocation API

The geolocation API allow you to locate users. The techniques for geolocation vary depending on which technique is available, GSM triangulation, GPS localization, WiFi triangulation or IP geolocation via a database.

With the watchPosition function you can track users, if the position changes the callback will be executed. To stop watching geolocation changes you call clearWatch.

Geolocation API w3c page

you can try this geolocation api example

web workers API

Web workers allow you to put heavy tasks like calculations in threads, to make them run in the background and therefore don't make the user wait for them to finish. You can listen to web workers and get a notice when their work is done.


<script>
    var worker = new Worker('worker.js');
    worker.onmessage = function (event) {
        document.getElementById('result').textContent = event.data;
    };
</script>
                    

The w3c web workers editors draft which already had some good examples to get started

A very good article about web workers can be found on html5rocks and another one can be found on the mozilla developer zone

application cache (offline mode API)

Another html5 feature is the offline ode which allows you to make your website available offline. This can be useful for mobile users.

To use the offline mode you need create a manifest file and add a the manifest attribute to the html tag of your page, the manifest attribute value is the path to your manifest file.


<html lang="en" manifest="my.manifest">
                        

More informations about the manifest can be found in the mozilla developer zone and on html5rocks

From w3c: If the manifest's scheme is https: or another scheme intended for encrypted data transfer, then all URLs in explicit sections must have the same origin as the manifest itself.

CACHE MANIFEST
# 2012-0-22:v3.1

CACHE:
/favicon.ico
index.html
stylesheet.css
images/logo.png

NETWORK:
chat.js
http://google-analytics.com/ga.js

FALLBACK:
/login login.html
                        

The manifest file has three sections.

NETWORK is for resources that you don't want to make available offline like a javascript file used to do track user statistics.

CACHE is a list of all the files you want to make available offline.

FALLBACK a list of files that were available online like a login page which you want to replace by a special offline version of that page.

While downloading the files listed in your manifest your browser will fire out progress events you can listen to and which tell you how much files have already been downloaded. It will fire even more events when download starts, finishes or noupdate if nothing new got downloaded because all files are already in your browser cache.

local storage API

The local storage allow you to save key / value pairs locally in your browser. Those informations persist even if the user closes his browser. Those informations can not be read by another website that is hosted on another domain because of the same origin policy. Unlike cookies the information in the storage never gets transmitted to the server.


localStorage.length;
localStorage.key(n);
localStorage.getItem(key);
localStorage.setItem(key,data);
localStorage.removeItem(key);
localStorage.clear();
                    

session storage API

The session storage is like the local storage but the data doesn't persist if the user closes his browser.


var cnt = sessionStorage.length;
sessionStorage.key(n);
sessionStorage.getItem(key);
sessionStorage.setItem(key,data);
sessionStorage.removeItem(key);
sessionStorage.clear();
                    

file API / filesystem API

Using the fileapi you can now listen to the progress events and display the progress to users using a progress bar. You can preview images before they get uploaded. You can even create files, for example you can create thumbnails of images even before the user clicks the upload button.


<input type="file" id="input" multiple onchange="handleFiles(this.files)">
                        

The w3c html5 file API draft and here is the filesystem API w3c page.

Lots of informations and code examples can be found on the mozilla developer zone.

Here is a file upload drag and drop demo and html5rocks has an article that explains howto use the file api and create a drag and drop upload field.

Yet again on html5rocks is a very good article about the filesystem API.

fullscreen API

The fullscreen API allows you to put any html element in fullscreen mode.

A good article about the fullscreen API can be found on html5rocks

webRTC / getUserMedia() API

getUserMedia() or the prefixed webkit version webkitGetUserMedia() also called the device API, is a function that will allow us to build great web apps in the future, but it's not part of HTML5. A good source of informations is the webRTC w3c editors draft

getUserMedia() can be used to access the users webcam, the video stream can be displayed in a canvas element and therefore be modified in real time using canvas functionality. Opera is the has a nice example.

The w3c editors draft can be found here.


// Replace the source of the video element with the stream from the camera
var video = document.getElementById('sourcevid');
if (navigator.getUserMedia) {
    navigator.getUserMedia('video', successCallback, errorCallback);
    function successCallback(stream) {
        video.src = stream;
    }
    function errorCallback(error) {
        console.error('An error occurred: [CODE ' + error.code + ']');
        return;
    }
} else {
    console.log('Native web camera streaming (getUserMedia) is not supported in this browser.');
    return;
}
                        
With the webRTC standard you could easly create a web app like chat-roulette.

query selectors

With html4 you could use getElementById , now with html5 you can the two newcomers querySelector and querySelectorAll


var domNode = document.querySelector('.classA', '.classB');
var domNodes = document.querySelectorAll('.classA', '.classB');
                    

web sockets

Web sockets allow you to build a bi-directional communication channel to a socket of your server. That connection stays open for as long as you want, you can send data as often as needed to the server. The server can push answers to the client every time he wants, the server doesn't need to wait for the client to ask something.

An application that needs such a feature is a chat. An ajax chat would have to check every second if there is a new message an the server that got written by another user using an ajax request. With web sockets all you need to do is open a connection and wait for incoming messages by the server.


    <script>
        conn = new WebSocket('ws://nodejs.example.com:9999');    
        conn.onmessage = function (event) {
            var message = event.data; 
        }
    </script>
                        

The web sockets specification from w3c. There are also two interesting articles on the mozilla developer zone and html5rocks and a demo can be found on html5demos.com.

cross-window messaging

Cross-window messaging is a new technique that allows you to send messages to other tabs opened in your browser.

A nice article from John Resig about cross-window messaging

XMLHttpRequest (Level2)

Your right if you think that xmlhttprequest are nothing new, the news is the level2 suffix.

The most important new advantages of xhr2 are a standardized technique, xhr file transfer (ajax file upload) and cross domain xhr requests.


<script>
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://www.example.com/hello.json');
    xhr.onload = function(e) {
        var data = JSON.parse(this.response);
    }
    xhr.send();
</script>
                        

The w3c xmlhttprequest working draft.

A good article about the xhr2 can be found on html5rocks with examples for file uploads using xhr, sending data to the server and even howto request data from a different origin.

contenteditable attribute

This new feature allows you make elements editable, like a div containing some text.

The w3c's description of this new feature. A very good article about contenteditable can be found at html5doctor. A small demo can be found on this page.

You may wonder for what this is usefull, if we already have forms or what you should done after then content got edited. I think the idea is to listen to changes using javascript, for example for keypress events on the contenteditable div and then send those changes to the server by using ajax. You could also record changes using javascript and then do some interaction with another page content or some other fancy things using javascript.


<div contenteditable=true>example</div>
                        

spellchecker attribute

The w3c's description of this new feature as well as the whatwg.org website.

I think there isn't much i have to explain about this new feature, i guess you know what a spellchecker is ;)

Apparently you can't set a language. The language used by the spellchecker is the main language of the users browsers. So even if you set the language in the html tag using the attribute lang, the spellchecker will ignore it. Something else which is not great is that the spellchecker does not suggest you correct spelling by putting a select box under the word, you have to do a right click on the word to get a list of corrected words.

SVG

SVG (Scalable Vector Graphics) is not part of html5, but still new for a some browsers and interesting. SVG is an XML markup language for describing two-dimensional vector graphics.

More informations about SVGs can be found on the mozilla developer zone and lots of examples can be found on w3schools example page

A cool new feature that you might encounter in the future are SVG filters, that can be for example applied to a HTML5 video or images.

The w3c recommendation can be found on this page

webSQL

This API is not active anymore, if you want more details take a look at the w3c webdatabase specification.

The w3c decided to stop working on this specification because of a lack of different implementation ways. Every vendor that supported it used SQLite as the backend. Therefore the w3c was unable to test different implementations and stopped the working group.

In my opinion is very sad for the web not to have something like an SQL Database in the browser, but i don't blame anyone because i can understand why the w3c stopped their work and i can understand the browser vendors for all choosing SQLite as backend, writing and supporting an own backend can be a lot of work.

Beware. This specification is no longer in active maintenance and the Web Applications Working Group does not intend to maintain it further.

frame / iframe

Just to clarify this, iframe's are still part of html5 but frames are not.

CSS3

There are a lot of new and exciting things going on in the CSS3 world, i won't present you all, but here are some i like a lot.

If you want to use CSS3 stuff today and still want to support IE, you will have to use polyfills like the next two, CSS3 PIE to get support for box-shadow, border-radius, multiple-backgrounds, gradients and more in IE6-9 and selectivizr to get css3 selectors support in IE6-8.

RGBA

RGB colors were already part of previous CSS versions, but what's new in CSS3 is that you can now also specify the alpha value. This value controls the opacity of a color, where 1 is fully opaque (visible) and 0 totally invisible (transparent).


<style>
    p { background-color: rgba(255, 0, 0, 0.2); position: absolute; left: 50px; width: 100px; height: 300px; z-index: 2; }
    div { background-color: rgba(0, 0, 255, 0.5); position: absolute; top: 50px; width: 300px; height: 100px; z-index: 3; }
    span { background-color: rgba(0, 255, 0, 0.8); position: absolute; top: 200px; width: 300px; height: 100px; z-index: 1; }
</style>
                        

text-shadow

This is a nice addition to the growing list of CSS features, it adds a nice background effect to your text.

x-coordinate, y-coordinate, blur radius, color


<style>
    p { text-shadow: 1px 1px 0px #b7d0de, 1px 2px 0px #9595a6; font-size: 26px; }
    div { text-shadow: 2px 2px 2px black; font-size: 26px; }
</style>
                        

box-shadow

Same as text-shadow but for boxes ;)

x-coordinate, y-coordinate, blur radius, color


<style>
    div { box-shadow: 5px 5px 7px #f2af2a; border: 1px solid #f2af2a; width: 100px; height: 100px; margin: 50px; }
</style>
                        

gradients

gradients made with CSS, no need to create an image in gimp anymore.

For linear gradients you define a direction or angle, the start color and an unlimited number of stop colors. Optionally you can also define a length per color (with the length you can change the natural position where a color would start by a value you think is better, in percent).

For radial gradients the syntax is similar but slightly more complex, first you define a position where the gradient should start, second parameter is the type of shape (circle or ellipse) and optionally it's size (closest-side, farthest-side, closest-corner, farthest-corner), then like for linear gradients an unlimited number of color stops.

Radial and linear gradients can also repeat their colors indefinitely, by using the repeating gradients functions for either repeating linear or radial gradients.

Nice write-ups for gradients can be found on impressive webs and on css3files.com.

Here is a nice tool that let's you play with gradients to help you quickly find the gradient you want to use: http://gradients.glrzad.com/ or http://www.colorzilla.com/gradient-editor/.

The w3c draft for gradients is a good source of information.

Using the radial gradient for the body background was tricky, a good solution can be found in a stackoverflow post.


<style>
    html {
        height: 100%;
    }
    body { 
        background-image: -webkit-radial-gradient(center, circle closest-side, yellow, blue);
        background-image: -moz-radial-gradient(center, circle closest-side, yellow, blue);
        width: 100%;
        height: 100%;
        margin: 0;
        background-repeat: no-repeat;
        background-attachment: fixed;
    }
</style>
                        

<style>
    body { 
        background-image: -webkit-linear-gradient(top left, yellow, blue);
        background-image: -moz-linear-gradient(top left, yellow, blue);
    }
</style>
                        

font-face

Font face allows you to embed fonts that are not yet on the users computer. Finally you can use whatever font you want in your web-pages, define an source for the font, if the user doesn't have that font the browser will download it from your server.

Google made a portal with lots of free web fonts.

Together with typekit google developed the font loader, which makes embedding fonts really easy and allow you to download the fonts asynchronously.


<style>
    @font-face {
        font-family: 'Shojumaru';
        font-style: normal;
        font-weight: 400;
        src: local('Shojumaru'), local('Shojumaru-Regular'), url(https://themes.googleusercontent.com/static/fonts/shojumaru/v2/pYVcIM206l3F7GUKEvtB3T8E0i7KZn-EPnyo3HZu7kw.woff) format('woff');
    }
    p {
        font-family: 'Shojumaru', cursive;
        font-size: 36px;
    }
</style>
                        

media queries

The media queries are not new but have been enhanced. They are very helpful when it comes to creating a responsive web-app, where you want to build pages that adapt themself depending of mainly screen size. But not exclusively, you can also check for orientation (landscape / portrait), aspect-ratio and some more. For a complete list check the w3c page.

two good video tutorial can be found on nettuts and another one on about.com.

IE (< 9) does not support media queries, to enable this feature in IE you could use the following javascript polyfill.

examples of websites that use media queries can be found at http://mediaqueri.es/.


    <style>
        @media screen and (max-width: 480px) { p { background-color: red; } }
        @media screen and (min-width: 481px) and (max-width: 960px) { p { background-color: green; } }
        @media screen and (min-width: 961px)  and (max-width: 1024px) { p { background-color: blue; } }
        @media screen and (min-width: 1025px) { p { background-color: black; } }
    </style>
                        

media queries example

transitions

Transitions are easy to use but what you get can be pretty nice. The main advantage is that transitions let you transition from one state to another. All you have to do is set the CSS property you want to transition from its initial state to another state i will have let's say on hover. Another property is the duration of the transition. You can also use a function to calculate intermediate values and finally you can define a delay that the transition should wait before starting.

A good guide about transitions can be found on this page.


<style>
    #ex1 {
        background-color: brown;
        color: yellow;
        margin-bottom: 20px;
    }

    #ex1:hover {
        -moz-transition-property: background-color, color;
        -moz-transition-duration: 3s;
        -moz-transition-timing-function: ease-out;
        -webkit-transition-property: background-color, color;
        -webkit-transition-duration: 3s;
        -webkit-transition-timing-function: ease-out;
        background-color: yellow;
        color: brown;
    }

    #ex2 {
        -moz-transition-property: background-color, color;
        -moz-transition-duration: 3s;
        -moz-transition-timing-function: ease-out;
        -webkit-transition-property: background-color, color;
        -webkit-transition-duration: 3s;
        -webkit-transition-timing-function: ease-out;
        background-color: blue;
        color: white;
        margin-bottom: 20px;
    }

    #ex2:hover {
        -moz-transition-property: background-color, color;
        -moz-transition-duration: 3s;
        -moz-transition-timing-function: ease-out;
        -webkit-transition-property: background-color, color;
        -webkit-transition-duration: 3s;
        -webkit-transition-timing-function: ease-out;
        background-color: white;
        color: blue;
    }

    #ex3 {
        border: 1px solid black;
    }

    #ex3:hover {
        -moz-transition-property: box-shadow;
        -moz-transition-duration: 3s;
        -moz-transition-timing-function: ease-out;
        -webkit-transition-property: box-shadow;
        -webkit-transition-duration: 3s;
        -webkit-transition-timing-function: ease-out;
        -moz-box-shadow: 10px 10px 10px black;
        -webkit-box-shadow: 10px 10px 10px black;
    }
</style>
                        

animations

The new CSS3 animations are very powerful, but also complex to learn. They are to do animations, that can be as complex as flash. The CSS3 @keyframes rules let you gradually change the properties of a DOM node. The animation properties let you define default values to describe the animation.

Coding everything by hand can be heavily time consuming, but firms like Adobe will or already started creating animation tools that will make animating a lot easier. Take a look at their edge preview.

To find some cool CSS3 animation examples, just google for them, there is already a decent number of them out there.


<style>
    @keyframes resize {
            0% {
                    padding: 0;
            }
            50% {
                    padding: 0 20px;
                    background-color:rgba(255,0,0,0.2);		
            }
            100% {
                    padding: 0 100px;
                    background-color:rgba(255,0,0,0.9);
            }
    }

    #box {
            animation-name: resize;
            animation-duration: 1s;
            animation-iteration-count: 4;
            animation-direction: alternate;
            animation-timing-function: ease-in-out;
    }
</style>
                        

transformations

Transformations do exactly what the name supposes. They allow you to transform a DOM node.

A nice example of transformations used to create a rotating (3d like) cube, made of different images transformed to make a cube. All of desandro's examples can be found on this github page.


<style>
    p {
        -webkit-transform: rotate(30deg);
        /*
        -webkit-transform: rotateX(130deg);
        -webkit-transform: rotateY(130deg);
        */
    }
</style>
                        

For more details read the w3c CSS3 Transforms working draft.

css3 selectors

An important part of the new css3 standard are the new selectors, they will allow you to create more powerfull stylesheets.

For more informations i recommend reading the new selectors w3c recommendation.

A good description of these new selectors can be found in this article

Vendor Prefixes

Not every browser supports the same CSS properties. That's why every browser has it's own vendor prefix. A browser uses a prefix for CSS properties that are not a standard yet, but have the draft status. This allows developers to use those properties and test them. Then maybe in the future if all browser is willing the implement the property it will become a w3c standard.

I hate vendor prefixes, they increase the size of your CSS files by a lot if you use them, which is bad because you have to type more code and afterwards your users have to download bigger files which results in slower page loading times.

  • -o (Opera)
  • -ms (IE)
  • -moz (Firefox)
  • -webkit (Safari / Chrome)

A list of vendor prefixed properties can be found on this page

Why should i use HTML5 today?

  • Because lots of features degrade gracefully, modern browser will support the features other browsers will ignore them or fall back to another technology.
  • Smartphone browsers support HTML5
  • There are stores for HTML5 apps, like the Mozilla Marketplace or the Chrome Web Store
  • There are operating systems like Chromium OS and Mozilla's Boot2Gecko that are for HTML5 webapps only.
  • Create Windows8 Metro UI interfaces using HTML5 and Javascript

Why shouldn't i use HTML5 today?

  • Because lots of features are in two works and not ready for production, those features may change in the future or their support will be removed alltogether, if that happens you have to rewrite your code
  • You can't just use HTML5 right now, you have to check for HTML5 support and then use lots of fallback and polyfill tools to support older browsers which results in higher development costs

Interesting Tools and Resources

Github social codings has lots of interesting projects to enhance your html5 / CSS3 website.

https://github.com/

You have a question about a web technology, ask stackoverflow users or find the answer by searching for someone asking a similar question:

http://stackoverflow.com/

CSS3 examples with browser compatibility informations:

http://css3clickchart.com

Wonder when you will be able to use a certain feature, then ask caniuse:

http://caniuse.com/

Also very useful to check whatever feature is safe to use is:

http://html5please.us/

Check if your browser can handle a feature:

http://platform.html5.org/

An html5 mobile comparison chart:

http://mobilehtml5.org/

Check if your browser has a feature or use a fallback method instead with modernizr:

http://www.modernizr.com/

Need a template to start with html5, check out html5 boilerplate:

http://html5boilerplate.com/

w3c validator:

http://validator.w3.org/

twitter bootstrap:

http://twitter.github.com/bootstrap/

html5rocks slides:

http://slides.html5rocks.com/#landing-slide

html5test (test your browser)

http://html5test.com/

html5 doctor:

http://html5doctor.com/

dive into html5:

http://diveintohtml5.info/

CSS3:

http://www.css3.info/

html5 demos:

http://html5demos.com/

convert flash to html5:

http://www.google.com/doubleclick/studio/swiffy/

http://labs.adobe.com/technologies/wallaby/

adobe edge:

http://labs.adobe.com/technologies/edge/

the w3c html5 mailinglist

the w3c html5 mailinglist

Books:

HTML5: Up and Running

image of book: HTML5: Up and Running

Pro HTML5 Programming: Powerful APIs for Richer Internet Application Development

image of book: Pro HTML5 Programming: Powerful APIs for Richer Internet Application Development

Introducing HTML5 (2nd Edition)

image of book: Introducing HTML5 (2nd Edition)

copyright

http://creativecommons.org/publicdomain/zero/1.0/

http://www.openwebfoundation.org/


author

Chris Weber

chris.lu