HTML5 po ruce a do kapsy


Zkratky (aby byl seznam čitelnější):
$new=document.createElement $bool=function(any){return!(any=="no"||!any)}
Většina nových funkcí může být detekována JavaScriptem. Pokud chcete otestovat podporu videa, vytvořte prvek <video>
a otestujte, zda v DOM má potřebné vlastnosti: if("canPlayType" in $new("video")){...}
Viz kapitola 2: Detekujeme podporu HTML5
.

Nové elementy

5 > 2 Formuláře

Viz kapitola 3: What Does It All Mean? Zpětně kompatibilní s HTML 4. Viz kapitola 9: A Form of Madness.
Test podpory Test podpory
<command> "type" in $new("command") Ověřování "noValidate" in $new("form")
<datalist> "options" in $new("datalist") Kontrola regulárními výrazy "pattern" in $new("input")
<details> "open" in $new("details") Textová nápověda (placeholder) "placeholder" in $new("input")
<output> "value" in $new("output") Autofokus "autofocus" in $new("input")
<progress> "value" in $new("progress") Required "required" in $new("input")
<meter> "value" in $new("meter") Nové typy vstupních polí Prohlížeče mohou si mohou přízpůsobit vzhled nebo způsoby vstupu.
<time> "valueAsDate" in $new("time") type="search" vyhledávání
Textové anotace <ruby>, <rt>, <rp> type="number" spinbox
Sémantické prvky Použitelné ve všech prohlížečích. IE < 9 potřebuje záplatu. type="range" šoupátko
<article>, <aside>, <header>, <hgroup>, <footer>, type="color" výběr barev
<section>, <nav>, <figure>, <figcaption>, <mark>, type="tel" telefonní číslo
<summary> type="url" adresa webu
Nově dokumentované <embed>, <keygen>, <wbr> type="email" e-mailová adresa
Zastaralé Stále podporované, ale nedoporučené. type="date"/"time"/"month"/"week"/"datetime"
<basefont>, <big>, <center>, <font>, <s>, <strike>, Test nových typů vstupních polí Všechny testy fungují podle stejného vzoru.
<frame>, <frameset>, <noframes>, <applet>, <dir>, function() {
<isindex>, <tt>, <u>, <acronym> (use <abbr>)   var i = $new("input");

Vždy dávejte atributy do uvozovek, pokud ovšem nejste celebrita. Klidně si pište do nepárových značek lomítka, pokud chcete. Z nezapomeňte, že validování rozhodně nevyšlo z módy: html5.validator.nu

  i.setAttribute("type", "search");
  return i.type !== "text";
}
Některé prohlížeče „podporují“ vstupní typy, ale nenabízejí uživatelské rozhraní.
Modernizr.js je dokáže detekovat.

Hele, mami, bez pluginů... Multimedia

Video můžete zakódovat pomocí Firefogg (Theora), HandBrake (H.264) nebo Miro Video Encoder (víc najednou). Viz kapitola 5: Video on the Web.
Podpora pro <audio> "canPlayType" in $new("audio")
Vorbis $bool($new("audio").canPlayType('audio/ogg; codecs="vorbis"'))
MP3 $bool($new("audio").canPlayType('audio/mpeg;'))
AAC $bool($new("audio").canPlayType('audio/mp4; codecs="mp4a.40.2"'))
<video> support "canPlayType" in $new("video")
WebM $bool($new("video").canPlayType('video/webm; codecs="vp8, vorbis"'))
Theora $bool($new("video").canPlayType('video/ogg; codecs="theora"'))
H.264 $bool($new("video").canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"'))
Vlastnosti Lze použít pro prvek <audio> i <video>.
src řetězec currentSrc řetězec, pouze ke čtení
preload řetězec tracks pole objektů TimedTrack
currentTime v sekundách buffered TimeRanges objekt, pouze ke čtení
initialTime v sekundách, pouze ke čtení played objekt TimeRanges, pouze ke čtení
duration v sekundách, pouze ke čtení seekable objekt TimeRanges, pouze ke čtení
startOffsetTime datetime, pouze ke čtení networkState výčtová hodnota, pouze ke čtení
paused boolean readyState výčtová hodnota, pouze ke čtení
ended boolean, pouze ke čtení error.code výčtová hodnota, pouze ke čtení
autoplay boolean

V jednom prvku <audio> i <video> můžete použít více prvků <source>. Prohlížeče podporující HTML5 nebudou vykreslovat dceřinné prvky značek <video>, můžete do nich vložit náhradí obsah (fallback) ve Flashi. Audio a video musí být nabízeny se správným MIME typep, nezapomeňte zkontrolovat vaše hlavičky Content-Type!

loop boolean
controls boolean
volume mezi 0.0 a 1.0, default = 1.0
muted boolean
playbackRate default = 1.0

Offline

IsGeolocationPartOfHTML5.com Geolokace

See Chapter 8: Let’s Take This Offline. Location sharing is always opt-in. See Chapter 6: You Are Here.
Test for support window.applicationCache Test for support navigator.geolocation
<html manifest> Links to cache manifest. Functions
Cache manifest sections Position getCurrentPosition(callback, err, opt);
CACHE: Always cached. No wildcards. long watchPosition(callback, err, opt);
NETWORK: Never cached. "*" wildcards. void clearWatch(watchId);
FALLBACK: Pairs; second is used offline. void callback(position); Called on success
Events First four are most common. void err(positionError); Called on error
checking always first PositionOptions object
downloading found manifest, fetching stuff timeout in milliseconds
progress still fetching stuff maximumAge also milliseconds
cached all resources cached enableHighAccuracy true or false
noupdate manifest hasn't changed Position object (in callback) has timestamp and coords.
updateready call swapCache() to activate Coordinates object Unsupported properties will be null.
obsolete manifest is 404 (or 410) latitude in decimal degrees
error it all went wrong somewhere longitude also decimal degrees

HTTP semantics still apply to resources listed in the cache manifest, so check your Expires and Cache-Control headers. Manifest must be served as text/cache-manifest, so check your Content-Type headers too. If any required resource fails to load, application will not work offline.

altitude meters above the reference ellipsoid
accuracy in meters
altitudeAccuracy also in meters
heading degrees CCW from true north
speed in meters/second
PositionError object (in err callback) has message and code:
TIMEOUT, POSITION_UNAVAILABLE,
PERMISSION_DENIED, or UNKNOWN_ERROR

Math is hard. Let’s go shopping! Canvas

Paths are like tracing in pencil; nothing is drawn until fill() or stroke()! See Chapter 4: Let’s Call It A Draw(ing) Surface.
Basic support "getContext" in $new("canvas")
Text support typeof $new("canvas").fillText=="function"
Functions Root path is implicit; subpaths must be explicit. drawImage() can also draw video or canvas.
beginPath(); drawImage(image,dx,dy,dw,dh); quadraticCurveTo(cpx,cpy,x,y);
closePath(); rotate(angle); bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y);
moveTo(x,y); translate(x,y); arc(x,y,radius,startAngle,endAngle,anticlockwise);
lineTo(x,y); arcTo(x1,y1,x2,y2,radius); getImageData(sx,sy,sw,sh);
rect(x,y,w,h); isPointInPath(x,y); putImageData(imagedata,dx,dy,x,y,w,h);
fill(); fillRect(x,y,w,h); fillText(text,x,y,maxWidth);
stroke(); strokeRect(x,y,w,h); strokeText(text,x,y,maxWidth);
clip(); clearRect(x,y,w,h); measureText(text);
save(); setTransform(a,b,c,d,e,f); createLinearGradient(x0,y0,x1,y1);
restore(); transform(a,b,c,d,e,f); createRadialGradient(x0,y0,r0,x1,y1,r1);
scale(x,y); createImageData(sw,sh); createPattern(image,repetition);
Properties All properties are read/write. fillStyle and strokeStyle can also be a gradient or pattern.
fillStyle CSS color, default = "black" shadowColor CSS color, default = "black"
strokeStyle CSS color, default = "black" shadowOffsetX in pixels, default = 0
font CSS font, default = "10px sans-serif" shadowOffsetY in pixels, default = 0
textAlign enumerated, default = "start" shadowBlur in pixels, default = 0
textBaseline enumerated, default = "alphabetic"

Learn about states! A canvas state includes the clipping path, all properties, and all transformations. save() pushes a state onto the stack and restore() pops it off.

globalAlpha 0.0 (transparent) to 1.0 (opaque)
lineWidth in pixels, default = 1
lineCap enumerated, default = "butt"
lineJoin enumerated, default = "miter"
miterLimit float, default = 10

Bits & Bytes

Doctype <!DOCTYPE html> Triggers standards-based rendering in all browsers. It’s 2011; stop relying on “quirks mode”!
Text encoding <meta charset="utf-8"> Always declare a charset, even if you’re a rockstar. UTF-8 is always a safe choice.
Optional end tags <html>, <head>, <body>, <li>, <p>, <dt>, <dd>, <colgroup>, <option>, <optgroup>, <rt>, <rp>,
<thead>, <tbody>, <tfoot>, <tr>, <td>. Exception: always close <p> before <table> to avoid IE weirdness.
Optional start tags <html>, <head>, <body>, <tbody>, <colgroup>. Amaze your friends! Skip the <html> tags and still validate!
New attributes <a media>, <a ping>, <base target>, <style scoped>, <script async>, <ol reversed>
Miscellaneous tests See The All-In-One Almost-Alphabetical No-Bullshit Guide to Detecting Everything.
IndexedDB window.indexedDB contentEditable "isContentEditable" in $new("a")
Web Workers window.Worker Drag-and-drop "draggable" in $new("span")
Web Sockets window.WebSocket File API typeof FileReader!=="undefined"
X-doc messaging window.postMessage Undo history typeof UndoManager!=="undefined"
Web SQL window.openDatabase <iframe sandbox> "sandbox" in $new("iframe")
Web Storage "localStorage" in window && window["localStorage"] !== null See Chapter 7: Local Storage.
History API window.history && window.history.pushState See Chapter 11: History API.
Inline SVG function() { var e=$new("div"); e.innerHTML="<svg></svg>";
  return window.SVGSVGElement && e.firstChild instanceof window.SVGSVGElement}

Serial Number 110518 Credits

Writing Mark Pilgrim References HTML5, HTML-diff, HTML vs. XHTML
Code Modernizr (Paul Irish et. al.) Inspiration Beagle Bros
Typography Chunk, Latin Modern License CC-BY-3.0