Estelle Weyl · Standardista.com · @estellevw ·Press key to advance. ·Press 2 for notes.

HTML5:
the Good Enough Parts

Estelle Weyl HTML5 & CSS3 for the Real World Mobile HTML5: Using the Latest Today by Estelle Weyl and Maximiliano Firtman

www.standardista.com
@estellevw

CSS

  • @font-face Web fonts
  • calc() in CSS
  • Generated content
  • Gradients
  • display values
  • Mulitiple backgrounds
  • background image properties
  • Border images
  • Border-radius
  • Box-shadow
  • Box-sizing
  • New Colors
  • Alphatransparency
  • Media Queries
  • Multiple column layout
  • object-fit/object-position
  • Opacity
  • CSS3 selectors
  • Text-shadow
  • Transforms
  • Transitions
  • 3D Transforms
  • Animation
  • Word-wrap
  • Flexible Box Layout Module
  • Grid Layout
  • rem (root em) units
  • Masks
  • Reflections (not a spec)
  • text-stroke
  • Text-overflow

HTML5

  • Semantic elements
  • Audio element
  • Canvas
  • contenteditable attribute
  • dataset & data-* attributes
  • Details & Summary elements
  • Drag and Drop
  • HTML5 form features
  • Form validation
  • Datalist element
  • Progress & Meter
  • New semantic elements
  • Offline web applications
  • Ruby annotation
  • Session history management
  • Text API for Canvas
  • Toolbar/context menu
  • Video element
  • WebGL - 3D Canvas graphics

JS API

  • Cross-document messaging
  • Cross-Origin Resource Sharing
  • File API
  • Geolocation
  • Hashchange event
  • IndexedDB
  • JSON parsing
  • Server-sent DOM events
  • Web Notifications
  • Web Sockets
  • Web Storage
  • Web Workers
  • Stream API
  • Web SQL Database
  • SVG

Other

  • classList (DOMTokenList )
  • Data URLs
  • getElementsByClassName
  • MathML
  • MPEG-4/H.264/WebM/VP8/Ogg/Theora video formats
  • querySelector/querySelectorAll
  • Touch events
  • WAI-ARIA Accessibility features
  • Font Formats
  • XHTML served as application/xhtml+xml
  • XMLHttpRequest 2
  • XHTML+SMIL animation

HTML5 Components

  • Doctype
  • Character Set
  • Type Attribute
  • Semantic elements
  • <figure> & <figcaption>
  • <details> & <summary>
  • Ruby annotation
  • contenteditable attribute
  • dataset & data-* attributes
  • HTML5 form features
  • Form validation
  • <datalist> element
  • <progress> & <meter>
  • <audio> element
  • <video> element
  • <canvas>
  • WebGL - 3D Canvas graphics

Old v. New Doctype

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html  xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta  http-equiv="Content-Type" content="text/html; charset=UTF-8 " />
<title>XHTML1 Strict Document</title>
<script  type="text/javascript" src="boo.js"></script>
<link  type="text/css" rel="stylesheet" href="a.css"/>
</head>
<body>
</body>
</html>

Minimalistic Syntax

<!DOCTYPE html>
<meta charset=UTF-8>
<title>Document Intentionally Blanks</title>
<!DOCTYPE html>
<title>Tweetable Docoument</title>
<p>Tweetable HTML5</p>
  • Short DTD
  • Short Charset
  • No ‘type’ attribute
  • <body> and <head> are inferred.

Non-Semantic Elements

<div id="header">
<div id="nav">
<div id="sidebar">
<div id="content">
<div class="article">
<div class="section">
<div class="section">
<div class="footer">

Semantic Elements

<header>
<nav>
<aside>
<div id="content">
<article>
<section>
<section>
<footer>

hgroup

<hgroup>
   <h1>This is my header</h1>
   <h2>This is my subtitle</h2>
<hgroup>
      

figure & figcaption

HTML5 & CSS3 for the Real World
My Book
<figure>
  <img src="htmlcss1.png" 
    alt="HTML5 &amp; CSS3 for the Real World"/>
  <figcaption>
     My Book
  </figcaption>
</figure> 

Details & Summary

<details>
   <summary>5 of 5 stars from three reviews</summary>
   <ul>
      <li>5 stars from Amazon</li>
      <li>5 stars from Costco</li>
      <li>5 stars from Barns &amp; Noble</li>
   </ul>
</details>

Example: Click below

5 of 5 stars from three reviews
  • 5 stars from Amazon
  • 5 stars from Costco
  • 5 stars from Barns & Noble
  • Chrome 12
  • Safari
  • Firefox 7
  • Opera 11
  • IE 10

New Elements

  • article
  • aside
  • audio
  • canvas
  • command
  • datalist
  • details
  • embed
  • figcaption
  • figure
  • footer
  • header
  • hgroup
  • keygen
  • mark
  • meter
  • nav
  • output
  • progress
  • rp
  • rt
  • ruby
  • section
  • source
  • summary
  • time
  • video
  • wbr

Changed Elements

  • <a>
  • <small>
  • <s>
  • <cite>
  • <i>
  • <b>
  • <u>
  • <hr>
  • <menu>
  • <input>
  • <meta>

Supporting Old Browsers

IE6-8 does not style elements that don't exist, so create the elements!

<!--[if IE]> 
<script type="text/javascript"> 
(function(){ 
  var html5elmeents ="article|aside|audio|canvas|...|video";
  html5elmeents.split('|'); 
  for(var i = 0; i < html5elmeents.length; i++){
    document.createElement(html5elmeents[i]); 
  } 
})(); 
</script> 
<![endif]-->  

Ruby annotation

"Ruby" are short runs of text alongside the base text, typically used in East Asian documents to indicate pronunciation or to provide a short annotation.

  • Chrome
  • Safari 5
  • Firefox 8
  • Opera 11.5
  • IE
  • <ruby> container for the next 2 elements
  • <rt> ruby text
  • <rp> ruby parenthesis
display: ruby | ruby-base | ruby-text | 
   ruby-base-container | ruby-text-container;

ruby-align: auto | start | left | center | end | right | 
   distribute-letter | distribute-space | line-edge;

ruby-overhang: auto | start | end | none;

ruby-position: before | after | right | inline;

ruby-span: attr(x) | none;

New Attributes

  • tabindex /* now applicable to any element (-1)
  • hidden /* no longer relevant */
  • contextMenu contextmenu="menuID"
  • spellCheck /* denotes errors */
  • data-* /* anything you want, accessible via dataset */
  • ContentEditable /* you can edit. accessible via the DOM */
  • draggable /* with the drag & drop API */
  • dropzone /* with the drag & drop API */
  • microdata attributes /* like microformats */
  • ARIA /* accessibility */

tabindex

<p tabindex="-1">Focusable with Javascript</p>
  • Every element can have tabindex
  • BUT: Maintaining source order is important
  • Only give a tabindex of -1
  • REASON: Enables element to be focusable with JS
    without changing ‘tab» order

contentEditable (& spellcheck)

<pre contenteditable>Look. I am editable>/pre>
I am editable

This paragrph has an error.

  • Chrome
  • Safari
  • Firefox 2
  • Opera
  • IE
  • iOS5, Android3, but not Opera or Android4
spellcheck="true | false"

data-* attributes

Define your own DOM manipulable data attributes

<div id="card27" data-cardID="27" data-row="3" data-col="2"></div>
var info = document.querySelector('#card27');
var cardinfo = [];
for (var key in info.dataset) {
  cardinfo.push(key, ': ', info.dataset[key], ',');
}
var currentCard = cardinfo.join('');

Result:

currentCard == 'cardID: 27, row: 3, col: 2'
var cardID = info.getAttribute('data-cardID'); //27

All browsers support "data-*"
'dataset' API starts with IE10, FF6, Saf5.1, Chr7, Op11.1

Microdata

Google processes RDFa, Microformats and Microdata.

  itemid
  itemprop
  itemref
  itemscope
  itemtype
person       url
nickname     affiliation(org)
photo        friend
title        contact
role         acquaintance
             address(adr)
<div itemscope itemtype="http://data-vocabulary.org/Person">  
 <img src="estelle.gif" itemprop="photo">  
  <p>Name: <i itemprop="name">Estelle Weyl</i>
  <p>Title: <i itemprop="title">Speaker, UI Engineer</i>   
  <p>Blog: <a href="http://standardista.com" itemprop="affliation">Standardista.   
  <p itemprop="address" itemscope  
    itemtype="http://data-vocabulary.org/Address">Address:   
    <i itemprop="locality">San Carlos</i>,  
    <i itemprop="region">CA</i></p>  
</div>

WAI-ARIA (examples)

W3C specs
  1. Roles
    • <div role="menubar"></div>
    • <div role="search"></div>
    • <div role="navigation">
    • role=application | menuitem | menuitemradio
  2. Live Regiouns
    • <div aria-live="assertive | polite | off">
  3. Widget Accessibility Attributes
    • aria-haspopup | aria-disabled ="true | false"
    • aria-controls | aria-describedby = "id"
    • aria-checked
  4. Tab index
    • <div tabindex="-1">

Web Forms

  • 13 new input types
  • New attributes
  • Native form validation
  • UI features
  • CSS pseudoclasses
<style>
  input:required {
    border: 1px solid red;
  }
  input:focus:invalid {
    background-color: pink;
  }
</style>

New Input Types

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

New input attributes

  • form
  • readonly
  • autocomplete
  • autofocus
  • list
  • pattern
  • required*
  • placeholder
  • multiple
  • list
  • min
  • max
  • step
  • formaction
  • formenctype
  • formmethod
  • formtarget
  • formnovalidate

Attribute Soup

<label for="name">Name: </label> 
<input id="name" name="inputName" 
  placeholder="placeholder text" 
  pattern="\w{6,9}" 
  required
  autofocus
  type="text"/>

Note that the following CSS is used in our live examples:

input:focus:invalid { background-color: lightPink;}
input:valid { background-color:lightGreen }
input:required {border: 2px solid red;}
input:optional {border: 2px solid green;}

Other form Elements

New Elements

  • <datalist>
  • <output>
  • <meter>
  • <progress>
  • <keygen>

list attribute and <datalist>

<label for="url">Web Address: </label>
<input id="url" type="url" name="url1" placeholder="www.domain.com" required  list="datalist1" />
  
<datalist id="datalist1">
  <option value="http://www.standardista.com" />
  <option value="http://www.oreilly.com" />
  <option value="http://www.evotech.net" />
</datalist>

  • Safari
  • Chrome
  • Opera
  • Firefox
  • IE10

<meter>, <progress> & <output>

<meter value=75 min=0 max=100 low=20 high=98>75%</meter>

Gas tank: 90% full

<progress>loading...</progress>

Please wait: loading...

<progress value="75" max="100">75% complete</progress>

Download is: 75% complete

<output>
  • Safari
  • Chrome
  • Opera
  • Firefox
  • IE 10

Audio & Video

<audio id="audio" src="sound.mp3" controls></audio>
document.getElementById("audio").muted = false;
<video id="video" src="movie.webm" autoplay controls></video>
document.getElementById("video").play();

Slide JS from HTML5Rocks
Nyan Cat from Saranj00n
Ode to IE6
Buttons from css3button.net

<audio>

Attributes

  • autoplay
  • preload = none | metadata | auto
  • controls
  • loop
  • mediagroup = string
  • src (required!)
  • muted?
  • buffer?

Children

  • <track>

<video>

Attributes

  • autoplay
  • preload = none | metadata | auto
  • controls
  • loop
  • poster
  • height
  • width
  • muted
  • mediagroup = string
  • src (required!)
  • autobuffer?
  • buffer?

Children

  • <track>

<video> example code

<video loop autoplay controls autobuffer 
      preload="metadata" poster="poster.jpg">
<source src="movie.ogg"  type='video/ogg; codecs="theora, vorbis"'>
<source src="movie.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
<source src="movie.webm" type='video/webm; codecs="vorbis,vp8"'>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,16,0" width="320" height="400">
      <param name="movie" value="movie.swf">
      <param name="quality" value="high">
      <param name="menu" value="true">
      <param name="LOOP" value="false">
        What browser are you using?
    </object>
    <track kind="caption" src="captions.srt"/>
</video>
<video src="movie.ogg">

<track>

<track>

  • child of a <video> or <audio>
  • links to a timed track or time-based data.
  • kind = subtitles| captions| descriptions| chapters | metadata,
  • Accessibility
<track kind=captions src=captions.srt>

canvas

Very basic canvas tutorial

SVG

WebGL

NOT READY!
  • Chrome 8
  • Safari 5.1
  • Firefox 4
  • Opera 12?
  • IE 10
  • Require hardware

Part 2: JavaScript APIs

  • Offline web apps
  • Web Storage
  • Indexed dataBase
  • Geolocation
  • Session history
  • Drag and Drop
  • JSON parsing
  • File API
  • Web Workers
  • Web Sockets
  • Server events
  • Web Notifications
  • getElementsByClassName
  • classList (DOMTokenList)
  • querySelector/querySelectorAll
  • Hashchange event
  • Cross-document messaging
  • Cross-Origin Resource Sharing
  • Touch events
  • Toolbar/context menu

Offline Web Applications

<!doctype HTML>
<html manifest="cache.manifest">
<meta charset="utf-8"/>
<title>...
CACHE MANIFEST
#version01

#files that explicitly cached
CACHE:
index.html
css/styles.css
scripts/application.js

#Resources requiring connectivity
NETWORK:
signin.php
dosomething.cgi
  • Chrome 8
  • Safari
  • Firefox 4
  • Opera
  • IE 10
  • Require hardware

ApplicationCache

Add to .htaccess file

AddType text/cache-manifest manifest
if(window.applicationCache){
 var appCache = window.applicationCache; 
 appCache.update();
 if (appCache.status == appCache.UPDATEREADY ){ 
      appCache.swapCache();
 }
}

localStorage

 
saveButton.addEventListener('click', function () {
  window.localStorage.setItem('value', textarea.value);
}, false);
textarea.value = window.localStorage.getItem('value');

Save text value on the client side (crash-safe)

	var el = document.querySelector('#myID');
	// place content from local storage on load if there is one
	el.innerHTML = window.localStorage.getItem('value');

Session Storage

  • use localStorage for persistent storage
  • use sessionStorage for per tab storage

Chrome: view storage: Inspector > Local Storage

  • Chrome
  • Safari
  • Firefox
  • Opera
  • IE 8
  • Well Supported!

Web SQL

var db = window.openDatabase("DBName", "1.0", "description", 5*1024*1024); 
  db.transaction(function(tx) {
  tx.executeSql("SELECT * FROM test", [ ], successCallback, errorCallback);
});

ChromeView your database: Inspector > Resources > Databases

    • Chrome
    • Safari
    • Firefox
    • Opera
    • IE 8
    • Well Supported!

    Index dB

    var indexDatabase = window.indexedDB.open('Database Name');
    indexDatabase.onsuccess = function(event) {
      var db = event.srcElement.result;
      var transaction = db.transaction([], IDBTransaction.READ_ONLY);
      var currRequest = transaction.objectStore('ObjectStore Name').openCursor();
      currRequest.onsuccess = ...;
    };
    
    
    • Chrome 11
    • Safari
    • Firefox 4
    • Opera
    • IE 10

    Geolocation

    function getLocation(){
      if (navigator.geolocation) {
      	  navigator.geolocation.getCurrentPosition(success, error);
    	  console.log('got position');
    	} else {
    	  error('not supported');
    	}
    }
    function error(text){
    	text = text || 'failed';
    	console.log(text); 
     }
    function success(location){
    	 var lat = location.coords.latitude;
    	 var long = location.coords.longitude;
    	 var url = "http://maps.google.com/maps?q="+ lat+","+long; 
    }
    • Chrome 4
    • Safari 5
    • Firefox 3.5
    • Opera 10.6
    • IE 9

    History API

    Load data & change browser address bar (without reloading)

    window.history.pushState(data, title, url) 
    /* Pushes data into history, with title, and, if provided, the URL.*/
    window.history.replaceState(data, title, url) /* Updates current history entry to given data, with title, and, if provided, URL */
    window.history.length /* number of entries in session history */
    
    window.history.state /* current state */
    
    window.history.go( Δ ) /*  back or forward Δ steps */
    
    window.history.back() /* Goes back one step Δ== -1*/
    
    window.history.forward() /* Goes forward one step Δ = 1*/

    Drag and Drop

    document.addEventListener('dragstart', function(event) {
      event.dataTransfer.setData('text', 'Customized text');
      event.dataTransfer.effectAllowed = 'copy';
    }, false);
    
    • HTML5 & CSS3 for the Real World
    • Drag this text or the image above to the right. You can even change this text.

    Drop Area
    • Chrome 8
    • Safari
    • Firefox 3.5
    • Opera 12?
    • IE
    • mobile: only Android

    File API

    • Import from the filesystem or the web.
    • Createstron new files from scratch.
    • Manipulate existing file data.
    • Store file data on the client.
    • Publish files back to the web.
    • Chrome 6
    • Safari
    • Firefox 3.6
    • Opera 11.1
    • IE 10
    • mobile: only Android

    Tutorial: Talk from Google I/O

    Web Workers

    Create additional javascript threads to run scripts in the background.

    • No access to DOM
    • Allows UI thread to continue

    Web Sockets

    • Full-duplex, bi-directional communication.
    • Both server and client can send data at any time or same time
    • Only data is sent, without HTTP headers (reduces bandwidth.

    JS Events and Methods

    var elements = document.getElementsByClassName(className)
    • Chrome 6
    • Safari
    • Firefox 3
    • Opera
    • IE 9
    • mobile: all
    var element = document.querySelector(selectors);
    var element = $(selectors)[0];
    
    var elements = document.querySelectorAll(selectors);
    var elements = $(selectors);

    Where 'selectors' is a comma separated list of CSS selectors

    • Chrome 6
    • Safari
    • Firefox 3
    • Opera
    • IE 8
    • mobile: all

    classList

    <article id="main" class="blogpost popup"></article>
    var el = document.getElementById('main').classList;
    var el = document.querySelector('#main').classList;
    el.add('bgimage');
    el.remove('blogpost'); el.toggle('popup'); console.log(el.contains('popup')); // false console.log(el.contains('blogpost')); // false console.log(el.classList.toString() == el.className); // true

    Result:

    <article id="main" class="bgimage"></article>
    • Chrome
    • Safari 5.1
    • Firefox
    • Opera
    • IE 10
    • mobile: Android 3, Opera 11.1

    Notifications

    if (window.webkitNotifications.checkPermission() == 0) {
      window.webkitNotifications.createNotification(picture, title, 
          content).show();
    } else {
      window.webkitNotifications.requestPermission();
    }

    • Chrome 12
    • Safari
    • Firefox 7
    • Opera 11
    • IE 10

    Thank you

    Estelle Weyl HTML5 & CSS3 for the Real World Mobile HTML5: Using the Latest Today by Estelle Weyl and Maximiliano Firtman

    www.standardista.com

    @estellevw