Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>
HTML5: Up and Running
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>
HTML5: Up and Running
Mark Pilgrim
Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo
Download from Library of Wow! eBook <>
HTML5: Up and Running by Mark Pilgrim Copyright © 2010 Mark Pilgrim. Production Editor: Adam Zaremba Copyeditor: Rachel Head Proofreader: Emily Quill
Indexer: Fred Brown Cover Designer: Karen Montgomery Interior Designer: David Futato
Download from Library of Wow! eBook <>
Table of Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix 1. How Did We Get Here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Diving In MIME Types A Long Digression into How Standards Are Made An Unbroken Line A Timeline of HTML Development from 1997 to 2004 Everything You Know About XHTML Is Wrong A Competing Vision What Working Group? Back to the W3C Postscript Further Reading
1 1 2 7 9 10 11 12 13 14 14
2. Detecting HTML5 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Diving In Detection Techniques Modernizr: An HTML5 Detection Library Canvas Canvas Text Video Video Formats Local Storage Web Workers Offline Web Applications Geolocation Input Types Placeholder Text Form Autofocus Microdata
15 15 16 16 17 18 19 21 23 23 24 25 27 27 28
v
Download from Library of Wow! eBook <>
Further Reading
29
3. What Does It All Mean? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Diving In The Doctype The Root Element The <head> Element Character Encoding Friends and (Link) Relations New Semantic Elements in HTML5 A Long Digression into How Browsers Handle Unknown Elements Headers Articles Dates and Times Navigation Footers Further Reading
31 31 33 34 35 36 41 42 45 47 49 51 52 54
4. Letâ€™s Call It a Draw(ing Surface) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 Diving In Simple Shapes Canvas Coordinates Paths Text Gradients Images What About IE? A Complete Example Further Reading
57 58 60 61 63 67 70 73 75 79
5. Video on the Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Diving In Video Containers Video Codecs H.264 Theora VP8 Audio Codecs MPEG-1 Audio Layer 3 Advanced Audio Coding Vorbis What Works on the Web Licensing Issues with H.264 Video vi | Table of Contents
Download from Library of Wow! eBook <>
81 81 83 84 84 85 85 86 87 87 88 90
Encoding Ogg Video with Firefogg Batch Encoding Ogg Video with ffmpeg2theora Encoding H.264 Video with HandBrake Batch Encoding H.264 Video with HandBrake Encoding WebM Video with ffmpeg At Last, the Markup MIME Types Rear Their Ugly Head What About IE? A Complete Example Further Reading
91 98 100 107 108 110 113 114 114 115
6. You Are Here (And So Is Everybody Else) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Diving In The Geolocation API Show Me the Code Handling Errors Choices! I Demand Choices! What About IE? geo.js to the Rescue A Complete Example Further Reading
117 117 118 120 121 123 123 125 126
7. The Past, Present, and Future of Local Storage for Web Applications . . . . . . . . . . 127 Diving In A Brief History of Local Storage Hacks Before HTML5 Introducing HTML5 Storage Using HTML5 Storage Tracking Changes to the HTML5 Storage Area Limitations in Current Browsers HTML5 Storage in Action Beyond Named Key/Value Pairs: Competing Visions Further Reading
127 128 129 130 131 132 132 134 135
8. Let’s Take This Offline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 Diving In The Cache Manifest Network Sections Fallback Sections The Flow of Events The Fine Art of Debugging, a.k.a. “Kill Me! Kill Me Now!” Let’s Build One! Further Reading
137 138 139 140 141 142 145 146
Table of Contents | vii
Download from Library of Wow! eBook <>
9. A Form of Madness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 Diving In Placeholder Text Autofocus Fields Email Addresses Web Addresses Numbers As Spinboxes Numbers As Sliders Date Pickers Search Boxes Color Pickers And One More Thing... Further Reading
147 147 148 150 151 153 155 156 158 160 160 161
10. “Distributed,” “Extensibility,” and Other Fancy Words . . . . . . . . . . . . . . . . . . . . . . . 163 Diving In What Is Microdata? The Microdata Data Model Marking Up People Introducing Google Rich Snippets Marking Up Organizations Marking Up Events The Return of Google Rich Snippets Marking Up Reviews Further Reading
163 164 165 168 174 176 180 184 185 189
Appendix: The All-in-One Almost-Alphabetical Guide to Detecting Everything . . . . . . . . 191 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
viii | Table of Contents
Download from Library of Wow! eBook <>
Preface
Diving In What is HTML5? HTML5 is the next generation of HTML, superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 provides new features that are necessary for modern web applications. It also standardizes many features of the web platform that web developers have been using for years, but that have never been vetted or documented plugins (Chapter 5) • Geolocation, whereby visitors can choose to share their physical locations with your web application (Chapter 6) • Persistent local storage without resorting to third-party plug-ins (Chapter 7) ix
Download from Library of Wow! eBook <> itself..
x | Preface
Download from Library of Wow! eBook <>: “HTML5: rendering may vary across browsers.. Download from Library of Wow! eBook <> Preface | xi
Download from Library of Wow! eBook <>
O’Reilly Media has uploaded this book to the Safari Books Online service. To have full digital access to this book and others on similar topics from O’Reilly and other publishers, signii | Preface
Download from Library of Wow! eBook <>
CHAPTER 1
How Did We Get Here?
Diving In.
MIME Types a number of headers before it sends the actual page markup. These headers are normally invisible, although there are a number of web development tools that will make them visible if you’re interested.
1
Download from Library of Wow! eBook <>
stylesheets have their own MIME type. Everything has its own MIME type. The Web runs on MIME types. Of course, reality is more complicated than that. Very early web servers .
A Long Digression into How Standards Are Made Why do we have an <img> element? I don’t suppose that’s a question you ask yourself very often. . thread described over the next several pages can be followed by clicking the “Next message” and “Previous message” links.
2 | Chapter 1: How Did We Get Here?
Download from Library of Wow! eBook <>, i.e., why not IMAGE= and SOURCE=. I somewhat prefer ICON since it implies that the IMAGE should be smallish, but maybe ICON is an overloaded word?
Midas was another early web browser, a contemporary of X Mosaic. It was crossplatform; it ran on both Unix and VMS. “SLAC” refers to the Stanford Linear Accelerator Center, now the SLAC National Accelerator Laboratory, which hosted the A Long Digression into How Standards Are Made | 3
Download from Library of Wow! eBook <> occurred.”. PRESENT
Embed this here when presenting it.
4 | Chapter 1: How Did We Get Here?
Download from Library of Wow! eBook <>
This proposal was never implemented, but the rel attribute is still around (see “Friends and (Link) Relations” on page 36). arbitrary “let’s put in a new tag <AUD SRC="">”.”
A Long Digression into How Standards Are Made | 5
Download from Library of Wow! eBook <>
Dave later wrote HTML 3.0, based on his earlier HTML+ draft. Outside of the W3C’s own reference implementation, Arena, HTML 3.0 was never implemented. It was superseded by HTML 3.2, which was also a “retro-spec”: “HTML 3.2 adds widely deployed features such as tables, applets and text flow around images, while providing full backward compatibility with the existing standard HTML 2.0.” Dave later coauthored with regard to Working Group., you’rescreen rendering technology codeveloped by Adobe and NeXT. This proposal was never implemented, but the idea that the best way to fix HTML is to replace it with something else altogether still pops up from time to time.
6 | Chapter 1: How Did We Get Here?
Download from Library of Wow! eBook <>.
HyTime was an early, SGML-based hypertext document system. It loomed large in many. themselves 
Download from Library of Wow! eBook <>
•. design. Before you read this chapter, had you ever heard of Andrew? Intermedia? HyTime? And HyTime was not some rinky-dink academic research project; it was an ISO standard approved for military use. It was Big Business. And you can read about it yourself. You can trace that through the Great
8 | Chapter 1: How Did We Get Here?
Download from Library of Wow! eBook <>
Browser Wars, all the way back to February 25, 1993, when Marc Andreessen offhandedly question, “Has W3C given up on HTML?” This waschartered the HTML Working Group to create this “suite of XML tagsets.” The members’ first step, in December 1998, was to draft,
Download from Library of Wow! eBook <> without displaying an error message. As you might expect, the fact that “broken” HTML markup still worked in web browsers?
Download from Library of Wow! eBook <>. requirements for this work: Backward (UAs) devicespecific way (e.g., unless included in XBL).
A Competing Vision | 11
Download from Library of Wow! eBook <> extensions to HTML and CSS and imperative extensions to DOM, to address medium level Web Application requirements, as opposed to sophisticated, fullyfledged OS-level APIs?” The vote was 11 to 8 against. In their summary of the work shop, the W3C’s members, registered the whatwg.org domain, and in June 2004, the WHAT Working Group was born.
What Working Group? What the heck is the WHAT Working Group? I’ll let it explain for backward compatibility with existing content. This group was created to ensure that future development?
Download from Library of Wow! eBook <>
Instead of scrapping over a decade’s worth of investment in HTML and making 99 percent those of their competitors. If that sounds like an insane amount of work, that’s because it is. Or rather, it was. It took Chapter 9.) Another was a draft specification called “Web Applications 1.0” that included major new features, like a direct-mode drawing canvas (see Chapter 4) and native support for audio and video without plug-ins (see Chapter 5).
Back to the W3C For several, and also in parallel XHTML. It will have a different chair and staff contact. It will work on HTML and XHTML together. We have strong support for this group, from many people we have talked to, including browser makers.
Back to the W3C | 13
Download from Library of Wow! eBook <>chart?
Download from Library of Wow! eBook <>
CHAPTER 2
Detecting HTML5 Features Download from Library of Wow! eBook <>
Diving In.
Detection Techniques:
Download from Library of Wow! eBook <>
For an example of testing which video formats are supported, see “Video Formats” Techniques” on page 15). If your browser supports the canvas API, the DOM object it creates 16 | Chapter 2: Detecting HTML5 Features
Download from Library of Wow! eBook <>
to represent a <canvas> element will have a getContext() method (see “Simple Shapes” on page 58). If your browser doesn’t support the canvas API, the DOM object it creates for a <canvas> element will have only the set of common properties, not anything. (see “Simple Shapes” on page 58), paths (see “Paths” on page 61), gradients (see “Grad
Download from Library of Wow! eBook <>
Shapes” on page 58). If your browser doesn’t support the canvas API, the DOM object it creates for a <canvas> element will have only the set of common properties, not anything() function introduced in the previous section: if (!supports_canvas()) { return false; }
If your browser doesn’t support the canvas API, it certainly won’t support the canvas text API!:
Download from Library of Wow! eBook <> you can use this to your advantage and tell them to play video through a third-party plug-in (see “Detection Techniques” on page 15). (see “Modernizr: An HTML5 Detection Library” on page 16) to detect support for HTML5 video: if (Modernizr.video) // let's play some } else { // no native video // maybe check for }
{ video! support available :( QuickTime or Flash instead
There is a separate test for detecting which video formats your browser can play, which I will demonstrate next.
Video Formats.
* See “A gentle introduction to video encoding, part 1: container formats” and “part 2: lossy video codecs” to learn about different video formats.
Video Formats | 19
Download from Library of Wow! eBook <> Adobe Flash, if you use a solution like Video for Everybody!.) The other codec is free and works in open source browsers like Chromium and Mozilla Firefox. Checking for video format support uses detection technique #3 (see “Detection Techniques” on page 15). from the previous section: if (!supports_video()) { return false; }
If your browser doesn’t support HTML5 video, it certainly won’t support any video formats! Next,"); return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
A “video format” is really a combination of several different things. In technical terms, you’re asking the browser whether it can play H.264 Baseline video and AAC LC audio in an MPEG-4 container.† The canPlayType() function doesn’t return true or false. In recognition of how complex video formats are, the function returns a string: "probably"
If the browser is fairly confident it can play this format
† I’ll explain what all that means in Chapter 5. You might also be interested in reading “A gentle introduction to video encoding”.
20 | Chapter 2: Detecting HTML5 Features
Download from Library of Wow! eBook <>
 to detect support for several different HTML5 video formats (note that Modernizr does not yet have support for detecting support for the open WebM video format): if (Modernizr.video) { // let's play some video! but what kind? if (Modernizr.video.ogg) { // try Ogg Theora + Vorbis in an Ogg container } else if (Modernizr.video.h264){ // try H.264 video + AAC audio in an MP4 container } }
Local Storage HTML5 Storage provides a way for websites websites can access it with JavaScript after the page is loaded.
Local Storage | 21
Download from Library of Wow! eBook <>
Ask Professor Markup Q: (see “Detection Techniques” on page 15). If your browser supports HTML5 Storage, there will be a localStorage property on the global window object. If your browser doesn’t support HTML5 Storage, the localStorage property will be undefined. You can check for local storage support using this function: function supports_local_storage() { return ('localStorage' in window) && window['localStorage'] !== null; }
Instead of writing this function yourself, you can use Modernizr (see “Modernizr: An HTML5 Detection Library” on page 16) to detect support).
Ask Professor Markup Q: How secure is my HTML5 Storage database? Can anyone read it? A: Anyone who has physical access to your computer can probably look at (or even change) your HTML5 Storage database. Within your browser, any website can read and modify its own values, but sites can’t access values stored by other sites. This is called a same-origin restriction.
22 | Chapter 2: Detecting HTML5 Features
Download from Library of Wow! eBook <>
Web Workers (see “Detection Techniques” on page 15). If your browser supports the Web Worker API, there will be a Worker property on the global window object. If your browser doesn’t support the Web Worker API, the Worker property will be undefined. This function checks for web worker support: function supports_web_workers() { return !!window.Worker; }
Instead of writing this function yourself, you can use Modernizr (see “Modernizr: An HTML5 Detection Library” on page 16) to detect support”).
Offline Web Applications Reading static web pages offline is easy: connect to the Internet, load a web page, disconnect from the Internet, drive to a secluded cabin, and read the web page at your leisure. (To save time, you may wish to skip the step about the cabin.) But what about using web applications like Gmail or Google Docs when you’re offline? Thanks to HTML5, anyone (not just Google!) can build a web application that works offline. Offline web applications start out as online web applications. The first time you visit an offline-enabled website, the web server tells your browser which files it needs in order to work offline. These files can be anything—HTML, JavaScript, images, even videos (see “Video” on page 18). Once your browser downloads all the necessary files, you can revisit the website even if you’re not connected to the Internet. Your browser will notice that you’re offline and use the files it has already downloaded. When you get back online, any changes you’ve made can be uploaded to the remote web server.
Offline Web Applications | 23
Download from Library of Wow! eBook <>
Checking for offline support uses detection technique #1 (see “Detection Techniques” on page 15). (see “Modernizr: An HTML5 Detection Library” on page 16) to detect support for offline web applications: if (Modernizr.applicationcache) { // window.applicationCache is available! } else { // no native support for offline :( // maybe try Gears or another third-party solution }
Note that JavaScript is case-sensitive. The Modernizr attribute is called applicationc ache (all lowercase), but the DOM object is called window.applicationCache (mixed case).
Geolocation: Is geolocation part of HTML5? Why are you talking about it? A: Geolocation support is being added to browsers right now, along with support for new HTML5 features. Strictly speaking, geolocation is being standardized by the Geo location Working Group, which is separate from the HTML5 Working Group. But I’m going to talk about geolocation in this book anyway, because it’s part of the evolution of the Web that’s happening now.
Checking for geolocation support uses detection technique #1 (see “Detection Techniques” on page 15).: 24 | Chapter 2: Detecting HTML5 Features
Download from Library of Wow! eBook <>
function supports_geolocation() { return !!navigator.geolocation; }
Instead of writing this function yourself, you can use Modernizr (see “Modernizr: An HTML5 Detection Library” on page 16) to detect support for the geolocation API: plug-in from Google that works on Windows, Mac, Linux, Windows Mobile, and Android. It provides a number of several mobile phone platforms, including BlackBerry, Nokia, Palm, and OMTP BONDI. Chapter 6 will go into excruciating detail about how to use all of these different APIs.
Input Types">
See for search boxes <input type="number">
See for spinboxes <input type="range">
See for sliders <input type="color">
See for color pickers <input type="tel">
See for telephone numbers <input type="url">
See for web addresses
Input Types | 25
Download from Library of Wow! eBook <>
 Techniques” on page 15). First, you create a dummy <input> element in memory: var i = document.createElement("input");
The default input type for all <input> elements is "text". This will prove to be vitally important. (see “Modern
Download from Library of Wow! eBook <> Techniques” on page 15)..
Download from Library of Wow! eBook <> websites. Also, browser vendors (or extension authors) can offer users a way to disable the autofocusing behavior. Checking for autofocus support uses detection technique #2 (see “Detection Techniques” on page 15).  alsoplaced
Download from Library of Wow! eBook <>
Checking for HTML5 microdata API support uses detection technique #1 (see “Detection • • • • • • • •
The <canvas> element The <video> element <input> types The <input placeholder> attribute The <input autofocus> attribute HTML5 Storage Web workers Offline web applications The geolocation API
JavaScript libraries: • Modernizr, an HTML5 detection library • geo.js, a geolocation API wrapper Other articles and tutorials: • • • •
Video for Everybody! “A gentle introduction to video encoding” “Video type parameters” The Appendix of this book
Further Reading | 29
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>.
31
Download from Library of Wow! eBook <>
This idea spread like wildfire, and soon all major browsers had two modes: “quirks mode” and “standards mode.” Of course, this being the Web, things quickly got out of hand. When Mozilla tried to ship Version 1.1 of its browser, the “Almost Standards mode,” which" "">.
32 | Chapter 3: What Does It All Mean?
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>
The two attributes here, lang and xml:lang, both define the language of this HTML page. en stands for “English.”*.
The <head> Element.
* Not writing in English? Find your language code at -language-tags.
34 | Chapter 3: What Does It All Mean?
Download from Library of Wow! eBook <>. In reality, it’s more complicated than that. Many characters are common to multiple encodings, but each encoding may use a different sequence of bytes to actually store those characters in memory or on disk. So, you can think of the character encoding as a kind of decryption key for the text. Whenever someone gives you a sequence of bytes and claims it’s “text,” you need to know what character encoding, very few authors actually have control over their HTTP servers. she" />
The <head> Element | 35
Download from Library of Wow! eBook <>.
Ask Professor Markup Q: several decades of poorly written software used by copy-and-paste–educated authors. You should always specify a character encoding on every HTML document, or bad things will happen. You can do it with the HTTP Content-Type header, the <meta httpequiv> declaration, or the shorter <meta charset> declaration, but please do it. The Web thanks you. subscribable format. • ...it’s a translation of this page into another language. • ...it’s the same content as this page, but in PDF format. • ...it’s the next chapter of an online book of which this page is also a part.. 36 | Chapter 3: What Does It All Mean?
Download from Library of Wow! eBook <>. <head> Element | 37
Download from Library of Wow! eBook <>="alter nate" document and now in HTML5, is to use the hreflang attribute.) Unfortunately, these errata were never reintegrated into the HTML 4 spec, because no one in the W3C HTML Working Group was working on HTML anymore.
Other link relations in HTML5 rel="archives"
() “indicates that the referenced document describes a collection of records, documents, or other materials of historical interest. A blog’s index page could link to an index of the blog’s past posts with rel="archives".”conforming synonym, provided for backward compatibility.) It also includes rel="prev" and rel="next", just like HTML 4 (and supports rel="previous", for backward com-
38 | Chapter 3: What Does It All Mean?
Download from Library of Wow! eBook <>
patibility),="style sheet". blogs. That didn’t happen, but rel="nofollow" persists. Many popular blogging systems default to adding rel="nofollow" to links added by commenters. rel="noreferrer"
() “indicates that no referrer information is to be leaked when following the link.” No shipping browser currently supports this, but support was recently added to WebKit nightlies, so it will eventually show up in Safari, Google Chrome, and other WebKit-based browsers. You can find a rel="noreferrer" test case at. rel="pingback"
() specifies the address of a “pingback” server. As explained in the Pingback specification, “The pingback system is a way for a blog to be automatically notified when other websites link to it. [...] It enables reverse linking —a way of going back up a chain of links rather than merely drilling down.” Blogging systems, notably WordPress, implement the pingback mechanism to notify authors that you have linked to them when creating a new blog post. The <head> Element | 39
Download from Library of Wow! eBook <>
rel="prefetch"
() “indicates that preemptively fetching and caching the specified resource is likely to be beneficial, as it is highly likely that the user will require this resource.” Search engines sometimes add <link rel="prefetch" href="<empha sis>URL OF TOP SEARCH RESULT</emphasis>"> Open Search document that describes how a browser could construct a URL to search the current site for a given keyword. OpenSearch (and rel="search" links that point to OpenSearch description documents) has been supported in Microsoft Internet Explorer since Version 7 and. You can find a rel="sidebar" test case at -sidebar.html. rel="tag"
() “indicates that the tag that the referenced document represents applies to the current document.” Marking up “tags” (category keywords) with the rel attribute was invented by Technorati to help in the categorization of.
40 | Chapter 3: What Does It All Mean?
Download from Library of Wow! eBook <>
New Semantic Elements in HTML5 HTML5 is not just about making existing markup shorter (although it does a fair amount of that). It also defines a number of new semantic elements. The following elements are defined by the HTML5 specification: <section> website’s home page could be split into different sections for the introduction, news items, and contact information.
, home page, and copyright page. The footer element alone is sufficient for such cases, without a nav element.
<article>
The article element represents>
The aside element represents a section of a page that consists of content that is tangentially related to the content around the aside element, and that.
<hgroup>
The hgroup element represents the heading of a section. The element is used to group a set of h1–h6 elements when the heading has multiple levels, such as subheadings, alternative titles, or taglines.
<header>
The header element represents a group of introductory or navigational aids. A header element is usually intended to contain the section’s heading (an h1–h6 element or an hgroup element), but this is not required. The header element can also be used to wrap a section’s table of contents, a search form, or any relevant logos.
<footer>er element contains entire sections, they represent appendixes, indexes, long colophons, verbose license agreements, and other such content.
<time>
The time element represents either a time on a 24-hour clock or a precise date in the proleptic Gregorian calendar, optionally with a time and a timezone offset.
<mark>
The mark element represents a run of text in one document marked or highlighted for reference purposes.
I know you’re anxious to start using these new elements, or you wouldn’t be reading this chapter. But first we need to take a little detour.
Download from Library of Wow! eBook <> New Semantic Elements in HTML5 | 41
Download from Library of Wow! eBook <>
A Long Digression into How Browsers Handle Unknown Elements Every browser has a master list of HTML elements that it supports. For example, Mozilla Firefox’s list is stored in nsElementTable.cpp. Elements not in this list are treated as “unknown elements.” There are two fundamental questions regarding unknown elements: How should the element be styled? By default, <p> has spacing on the top and bottom, <blockquote> is indented with a left margin, and <h1> is displayed in a larger font. What should the element’s DOM look like? Mozilla’s nsElementTable.cpp includes information about what kinds of other elements each element can contain. If you include markup like <p><p>, the second paragraph element implicitly closes the first one, so the elements end up as siblings, not parent and child. But if you write <p><span>, the span does. The first question should be relatively simple to answer: don’t give any special styling to unknown elements. Just let them inherit whatever CSS properties are in effect wherever they appear on the page, and let the page author specify all styling with CSS. Unfortunately, Internet Explorer (prior to Version 9) does not allow put a red border around the article. As I write this, Internet Explorer 9 is still in beta, but Microsoft has stated (and developers have verified) that Internet Explorer 9 will not have this problem..
42 | Chapter 3: What Does It All Mean?
Download from Library of Wow! eBook <>
Here is some ASCII art to showcase wondrousâ€™t recognize. For example: <html> <head> <style> article { display: block; border: 1px solid red } </style> <script>document.createElement("article");</script> </head> <body> <article> <h1>Welcome to Initech</h1> <p>This is your <span>first day</span>.</p> </article> </body> </html>
A Long Digression into How Browsers Handle Unknown Elements | 43
Download from Library of Wow! eBook <>capable browsers. Remy Sharp has done just that, with his aptly named “HTML5 enabling script”. The script has gone through several revisions, it. Still, this is enough to get Internet Explorer to treat these elements the way we want them to be treated when>
44 | Chapter 3: What Does It All Mean?
Download from Library of Wow! eBook <>
<![endif]--> </head>
Now we’re ready to start using the new semantic elements in HTML5.
Headers Let’s go back to our example page. Specifically, let’s look at very a number.
Headers | 45
Download from Library of Wow! eBook <> create a single node in the document outline. Given this markup:
46 | Chapter 3: What Does It All Mean?
Download from Library of Wow! eBook <>
.
Articles"
Articles | 47
Download from Library of Wow! eBook <>. 48 | Chapter 3: What Does It All Mean?
Download from Library of Wow! eBook <>.
Professor Markup Says.
Dates and Times This is exciting, right? I mean, it’s not “skiing down Mount Everest naked while reciting the Star Spangled Banner backward”: Dates and Times | 49
Download from Library of Wow! eBook <>
• A machine-readable timestamp • Human-readable text content • An optional pubdate flaghour format, then a timezone offset: <time datetime="2009-10-22T13:59:47-04:00" pubdate> October 22, 2009 1:59pm EDT </time>
The date/time format is pretty flexible. The HTML5 specification contains a number of
50 | Chapter 3: What Does It All Mean?
Download from Library of Wow! eBook <>
</a> </h1> </header> <p>Lorem ipsum dolor sit amet...</p> </article>
Navigation One of the most important parts of any website is the navigation bar. CNN.com has “tabs” along the top of each page that link to the different news sections—“Tech,” “Health,” “Sports,” etc. Google search results pages have a similar strip at the top of the page enabling you to try your search in different Google services—“Images,” “Video,” “Maps,” etc.: your sight is limited, and you use a dedicated program called a “screenreader” that uses text-tospeech: Navigation | 51
Download from Library of Wow! eBook <>
<nav> <ul> <li><a <li><a <li><a <li><a </ul> </nav>home</a></li>blog</a></li>gallery</a></li>about</a></li>
Ask Professor Markup Q: at skipnav..
Footers’s footer: a short copyright statement and a link to an about-theauthor page. Looking around at some popular sites, I see lots of footer potential: 52 | Chapter 3: What Does It All Mean?
Download from Library of Wow! eBook <> “Advertising Programs,” “Business Solutions,” and “About Google”; a copyright statement;
Download from Library of Wow! eBook <>
• Convert the <h3> headers to <h1>, since each will now be inside a sectioning element.?
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>)
Download from Library of Wow! eBook <>
Ask Professor Markup Q: Is there a 3D canvas? A: Not yet. Individual vendors have experimented with their own three-dimensional canvas APIs, but none: • The fillStyle property can be a CSS color, a pattern, or a gradient. (More on gradients shortly.) The default fillStyle is solid black, but you can set it to whatever
Download from Library of Wow! eBook <> • • • • • • • • • •
A set of off-white vertical lines A set of off-white horizontal lines Two black horizontal lines Two small black diagonal lines that form an arrow Two black vertical lines Two small black diagonal lines that form another arrow The letter “x” The letter “y” The text “(0, 0)” near the upper-left corner The text “(500, 375)” near the lower-right corner A dot in the upper-left corner, and another in the lower-right corner
Figure 4-2. Canvas coordinates diagram
60 | Chapter 4: Let’s Call It a Draw(ing Surface)
Download from Library of Wow! eBook <> drawing,: • moveTo(x, y) moves the pencil to the specified starting point. •); } for (var y = 0.5; y < 375; y += 10) { context.moveTo(0, y); context.lineTo(500, y); }
Paths | 61
Download from Library of Wow! eBook <>. Figure 4-3 shows the result.
Figure 4-3. A grid drawn on a canvas
Ask Professor Markup Q:.
62 | Chapter 4: Let’s Call It a Draw(ing Surface)
Download from Library of Wow! eBook <>, context.lineTo(60, context.moveTo(60, context.lineTo(60, context.moveTo(65, context.lineTo(60, context.lineTo(55,
0); 153); 173); 375); 370); 375); 370);white, and we’ll hardly be able to see them! The following lines change the color to black and draw the lines on the canvas: context.strokeStyle = "#000"; context.stroke();..
Text | 63
Download from Library of Wow! eBook <>, (see Figure 4-5 ).
*
64 | Chapter 4: Let’s Call It a Draw(ing Surface)
Download from Library of Wow! eBook <>
Figure 4-5. Text baselines);
The fillText() method draws the actual text: context.font = "bold 12px sans-serif"; context.fillText("x", 248, 43); context.fillText("y", 58, 165);
Ask Professor Markup Q: Can I use relative font sizes to draw text on a canvas? A: Yes. Like every other HTML element on your page, the <canvas> element itself has a computed font size based on your page’s CSS rules. If you set the context.font property to a relative font size like 1.5em or 150%, your browser multiplies this by the computed font size of the <canvas> element itself.
For the text in the upper-left corner, say we want the top of the text to be at y=5. But we’re lazy—we don’t want to measure the height of the text and calculate the baseline. Instead, we can set textBaseline to top and pass in the upper-left coordinate of the text’s bounding box: context.textBaseline = "top"; context.fillText("( 0 , 0 )", 8, 5);
Text | 65
Download from Library of Wow! eBook <>
Now for the text in the lower-right corner. Let’s say we want the bottom-right corner of the text to be at coordinates (492,370)—just a few pixels away from the bottomright corner of the canvas—but again, we don’t want to measure the width or height of the text. We can set textAlign to right and textBaseline to bottom, then call fillText() with the bottom-right coordinates of the text’s bounding box: context.textAlign = "right"; context.textBaseline = "bottom"; context.fillText("( 500 , 375 )", 492, 370);
Figure 4-6 shows the result.
Figure 4-6. Labeled axes on a canvas
Oops! We forgot the dots in the corners. We’ll see how to draw circles a little later; for now we’ll cheat a little and draw them as rectangles (see “Simple Shapes” on page 58): context.fillRect(0, 0, 3, 3); context.fillRect(497, 372, 3, 3);
And that’s all she wrote! Figure 4-7 shows the final product.
66 | Chapter 4: Let’s Call It a Draw(ing Surface)
Download from Library of Wow! eBook <>
Figure 4-7. A canvas coordinates diagram on a canvas
Gradients IEa
Firefox
Safari
Chrome
Opera
iPhone
Android
Linear gradients
7.0+
3.0+
3.0+
3.0+
10.0+
1.0+
1.0+
Radial gradients
·
3.0+
3.0+
3.0+
10.0+
1.0+
1.0+
a Internet Explorer support requires the third-party explorercanvas library.
Earlier in this chapter, you learned how to draw a rectangle filled with a solid color (see “Simple Shapes” on page 58), then a line stroked with a solid color (see “Paths” on page 61). But shapes and lines aren’t limited to solid colors. You can do all kinds of magic with gradients. Figure 4-8 shows an example. The markup looks the same as any other canvas: <canvas id="d" width="300" height="225"></canvas>
First, we need to find the <canvas> element and its drawing context: var d_canvas = document.getElementById("d"); var context = d_canvas.getContext("2d");
Gradients | 67
Download from Library of Wow! eBook <>)
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>:â€‚Letâ€™s Call It a Draw(ing Surface)
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>.src = "images/cat.png"; cat.onload = function() { context.drawImage(cat, 0, 0); }; </script>
The optional third and fourth parameters to the drawImage() method control image scaling. Figure 4-15 shows the same image of a cat,);
72 | Chapter 4: Let’s Call It a Draw(ing Surface)
Download from Library of Wow! eBook <>
} };
All this effort raises a legitimate question: why would you want to draw an image on a canvas in the first place? What does the extra complexity buy you over an <img> element and some CSS rules? Even the “multicat” effect could be replicated with 10 overlapping <img> elements. The simple answer is that you’d do this for the same reason you might want to draw text on a canvas (see “Text” on page 63). Our canvas coordinates diagram (see “Canvas Coordinates” on page 60) included text, lines, and shapes; the text-on-a-canvas element was just one part of a larger work. A more complex diagram could easily use drawImage() to include icons, sprites, or other graphics.
Download from Library of Wow! eBook <> Figure 4-15. Multicat!
What About IE? Microsoft Internet Explorer (up to and including Version 8, the current version at the time of writing) does not support the canvas API. However, Internet Explorer does support a Microsoft proprietary technology called VML, which can do many of the same things as the <canvas> element. And thus, excanvas.js was born.
What About IE? | 73
Download from Library of Wow! eBook <> 5</title> <!--[if IE]> <script src="excanvas.js"><vas> elements to your markup, or create them dynamically with JavaScript. Follow the instructions Explorerbased animation and other crazy stuff.
74 | Chapter 4: Let’s Call It a Draw(ing Surface)
Download from Library of Wow! eBook <>
There is one more caveat about using excanvas.js, and it’s a problem that I ran into while creating the examples in this chapter. ExplorerCanvas initializes its own fauxcanvas created a solitaire version of Halma with nineright corner of the board, in the least
Download from Library of Wow! eBook <>
Figure 4-16. Starting position of a Halma game++) {
76 | Chapter 4: Let’s Call It a Draw(ing Surface)
Download from Library of Wow! eBook <> || e.pageY) {). But we want coordinates relative to the canvas. We can get them as follows: x -= gCanvasElement.offsetLeft; y -= gCanvasElement.offsetTop;
Now we have x and y coordinates that are relative to the canvas (see “Canvas Coordinates” on page 60).Width), Math.floor(x/kPieceHeight)); return cell; }
Whew! Mouse events are tough. But you can use the same logic (in fact, this exact code) in all of your own canvas-based applications. Remember: mouse click→documentrelative coordinates→canvas-relative coordinates→application-specific code. OK, let’s look at the main drawing routine. Because the graphics are so simple, I’ve chosen to clear and redraw the board in its entirety every time anything changes within the game. This is not strictly necessary. The canvas drawing context will retain whatever
A Complete Example | 77
Download from Library of Wow! eBook <>. Here’s the board-clearing code: gDrawingContext.clearRect(0, 0, kPixelWidth, kPixelHeight);
The board-drawing routine should look familiar. It’s very similar to how we drew the canvas coordinates diagram (see “Canvas Coordinates” on page 60):clockwise). We can use the Math module that’s built into JavaScript to calculate radians:
78 | Chapter 4: Let’s Call It a Draw(ing Surface)
Download from Library of Wow! eBook <>.strokeStyle = "#000"; gDrawingContext.stroke();
What if the piece is selected? We can reuse nine circles, a few straight lines, and an onclick handler, we’ve created an entire game in <canvas>. Huzzah!
Further Reading • • • •
Canvas tutorial on the Mozilla Developer Center “HTML5 canvas—the basics”, by Mihai Sucan Canvas Demos: demos, tools, and tutorials for the HTML <canvas> element “The canvas element” in the HTML5 draft standard
Further Reading | 79
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>
CHAPTER 5
Video on the Web
Diving In plug-in—maybe QuickTime, maybe RealPlayer, maybe Flash. (YouTube uses Flash.) These plug-ins integrate with your browser well enough that you may not even be aware that you’re using them—until you try to watch a video on a platform that doesn’t support that plug-in, that is.. Table 5-1 shows which browsers support the <video> element at the time of writing. Table 5-1. <video> element support IE9
IE8
IE7
Firefox 3.5
Firefox 3.0
Safari 4
Safari 3
Chrome
Opera
✓
·
·
✓
·
✓
✓
✓
✓
Support for the <video> element itself is really only a small part of the story. Before we can talk about HTML5 video, you first need to understand a little about video itself. (If you know about video already, you can skip ahead to “What Works on the Web” on page 88.)
Video Containers You may think of video files as “AVI files” or “MP4 files.” In reality, “AVI” and “MP4” are just container formats. Just as a ZIP file can contain any sort of file within it, video
81
Download from Library of Wow! eBook <>
container formats only define how to store things within them, not what kind of data: MPEG-4 Usually with an .mp4 or .m4v extension. The MPEG-4 container is based on Apple’s older QuickTime container (.mov). Movie trailers on Apple’s website still use the older QuickTime container, but movies that you rent from iTunes are delivered in an MPEG-4 container. Flash Video Usually with an .flv extension. Flash Video is, unsurprisingly, used by Adobe Flash. Prior to Flash 9.0.60.184 (a.k.a. Flash Player 9 Update 3), this was the only container format that Flash supported. More recent versions of Flash also support the MPEG-4 container. Ogg Usually with an .ogv extension. Ogg is an open standard that is open source– friendly and is unencumbered by any known patents. Firefox 3.5, Chrome 4, and Opera 10.5 offer native support, without platform-specific plug-ins, for the Ogg container format, Ogg video (called “Theora”), and Ogg audio (called “Vorbis”). On the desktop, Ogg is supported out-of-the-box by all major Linux distributions, and you can use it on Mac and Windows by installing the QuickTime compo nents or DirectShow filters, respectively. It is also playable with the excellent VLC on all platforms. WebM With a .webm extension. WebM is a new container format that is technically very similar to another format called Matroska. WebM was announced at Google I/O 2010. It is designed to be used exclusively with the VP8 video codec and the Vorbis audio codec. (More on these in a minute.) It will be supported natively, without platform-specific plug-ins, in the next versions of Chromium, Google Chrome, Mozilla Firefox, and Opera. Adobe has also announced that the next version of Flash will support WebM video. Audio Video Interleave Usually with an .avi extension. The AVI container format was invented by Microsoft in a simpler time, when the fact that computers could play video at all was considered pretty amazing. It does not officially support many of the features of
82 | Chapter 5: Video on the Web
Download from Library of Wow! eBook <>.
Video Codecs When you talk about “watching a video,” you’re probably talking about a combination of one video stream and one audio stream. But you don’t have two different files; you just have “the video.” Maybe it’s an AVI file, or an MP4 file. As described in the preceding section, these are just container formats, like a ZIP file that contains multiple kinds of files within it. The container format defines how to store the video and audio streams in a single file. When you “watch a video,” your video player is doing several things at once: • Interpreting the container format to find out which video and audio tracks are available, and how they are stored within the file so that it can find the data it needs to decode next • Decoding the video stream and displaying a series of images on the screen • Decoding the audio stream and sending the sound to your speakers A video codec is an algorithm by which a video stream is encoded. That screenshots),. With a lossy video codec, information is irretrievably lost during encoding. Like copying an audio cassette tape, every time you encode you’re losing information about the source video and degrading the quality., and many offer ways to “cheat” and smooth over that blockiness during playback to make the loss less noticeable to the human eye.
Video Codecs | 83
Download from Library of Wow! eBook <>
There are tons of video codecs. The three most relevant codecs are H.264, Theora, and VP8.
H.264 H.264 is also known as “MPEG-4 part 10,” a.k.a. “MPEG-4 AVC,” a.k.a. “MPEG-4 Advanced Video Coding.” H.264 was developed by the MPEG group and standardized in 2003. It the Baseline profile, the AppleTV set-top box supports the Baseline and Main profiles, and Adobe Flash on a desktop PC supports the Baseline, Main, and High profiles. YouTube (owned by Google, my employer)PC devices that play H.264 video (including iPhones and standalone Blu-ray players) actually do the decoding on a dedicated chip, since their main CPUs are nowhere near powerful enough to decode the video in real time. Many desktop graphics cards also support decoding H.264 in hardware. There are a number of competing H.264 encoders, including the open source x264 library. The H.264 standard is patentencumbered; licensing is brokered through the MPEG LA group. H.264 video can be embedded in most popular container formats (see “Video Containers” on page 81), including MP4 (used primarily by Apple’s iTunes Store) and MKV (used primarily by noncommercial video enthusiasts).
Theora. By
84 | Chapter 5: Video on the Web
Download from Library of Wow! eBook <>
“native,” I mean “available on all platforms without platform-specific plug-ins.” You can also play Theora video on Windows or on Mac OS X after installing Xiph.org’s open source decoder software.
VP8 VP8 is another video codec from On2, the same company that originally developed VP3 (later Theora). Technically, it is similar in quality to H.264 Baseline, with lots of potential for future improvements.free,.
Audio Codecs Unless you’re going to stick to films made before 1927 or so, you’re going to want an audio track in your video. Like video codecs, audio codecs are encoding algorithms, in this case used for audio streams. As with video codecs, there are lossy and lossless audio codecs. And like lossless video, lossless audio is really too big to put on the Web, so I’ll concentrate on lossy audio codecs. Actually, we can narrow the focus even further, four plug-ins, speech-optimized audio codecs never really took off on the Web. So I’ll concentrate on general-purpose lossy audio codecs. As I mentioned in “Video Codecs” on page 83, when you “watch a video,” your computer is doing several things at once: 1. Interpreting the container format 2. Decoding the video stream 3. Decoding the audio stream and sending the sound to your speakers Audio Codecs | 85
Download from Library of Wow! eBook <>→encoding→decoding→listening makes you feel; and during decoding, both channels are decoded and each is sent to the appropriate speaker. Some audio codecs can handle more than two channels, and they keep track of which channel is which two (standardized in 1991). 86 | Chapter 5: Video on the Web
Download from Library of Wow! eBook <> Advanced Audio Coding is affectionately known as “AAC.” Standardized in 1997, it lurched into prominence when Apple chose it asenccomplexity” Vorbis is often called “Ogg Vorbis,” although this is technically incorrect—“Ogg” is just a container format (see “Video Containers” on page 81),. An droid mobile phones can also play standalone Vorbis audio files. Vorbis audio streams
Audio Codecs | 87
Download from Library of Wow! eBook <> the OggConvert encoder, the ffmpeg decoder, the aoTuV encoder, and the libvorbis decoder. There are also QuickTime components for Mac OS X and DirectShow filters for Windows.
What Works on the Web: • Mozilla Firefox (3.5 and later) supports Theora video and Vorbis audio in an Ogg container. • Opera (10.5 and later) supports Theora video and Vorbis audio in an Ogg container. • Google Chrome (3.0 and later) supports Theora video and Vorbis audio in an Ogg container. It also supports H.264 video (all profiles) and AAC audio (all profiles) in an MP4 container. • As of this writing (June 9, 2010), the “dev channel” of Google Chrome, nightly builds of Chromium, nightly builds of Mozilla Firefox, and experimental builds of Opera all support VP8 video and Vorbis audio in a WebM container. (Visit webm project.org for more up-to-date information and download links for WebMcompatible browsers.) • Safari on Macs and Windows PCs (3.0 and later) will support anything that QuickTime supports. In theory, you could require your users to install third-party QuickTime plug-ins. In practice, very few users are going to do that. So you’re left with the formats that QuickTime supports “out of the box.” This is a long list, but it does not include Theora video, Vorbis audio, or the Ogg container. However, QuickTime does support H.264 video (Main profile) and AAC audio in an MP4 container. • Mobile devices like Apple’s iPhone and Google Android phones support H.264 video (Baseline profile) and AAC audio (low-complexity profile) in an MP4 container.
88 | Chapter 5: Video on the Web
Download from Library of Wow! eBook <>
• Adobe Flash (9.0.60.184 and later) supports H.264 video (all profiles) and AAC audio (all profiles) in an MP4 container. • Internet Explorer 9 will support some as-yet-unspecified profiles of H.264 video and AAC audio in an MP4 container. • Internet Explorer 8 has no HTML5 video support at all, but virtually all Internet Explorer users will have the Adobe Flash plug-in. Later in this chapter, I’ll show you how you can use HTML5 video but gracefully fall back to Flash. Table 5-2 provides the above information in an easier-to-digest form. Table 5-2. Video codec support in shipping browsers
·
·
·
·
·
·
·
A year from now, the landscape will look significantly different: WebM will be implemented in multiple browsers, those browsers will ship nonexperimental WebMenabled versions, and users will upgrade to those new versions. The anticipated codec support is shown in Table 5-3. Table 5-3. Video codec support in upcoming browsers
a
b
9.0+a
4.0+
·
6.0+
11.0+
·
b
Internet Explorer 9 will only support WebM “when the user has installed a VP8 codec”, which implies that Microsoft will not be shipping the codec itself. Google has committed to supporting WebM “in a future release” of Android, but there’s no firm timeline yet.
And now for the knockout punch....
Professor Markup Says: What Works on the Web | 89
Download from Library of Wow! eBook <>
1. Make one version that uses Theora video and Vorbis audio in an Ogg container. 2. Make another version that uses WebM (VP8 + Vorbis). 3. Make another version that uses H.264 Baseline video and AAC low-complexity audio in an MP4 container. 4. Link to all three video files from a single <video> element, and fall back to a Flashbased video player.
Licensing Issues with H.264 Video Before we continue, I need to point out that there is a cost to encoding your videos twice. That is, in addition to the obvious cost—that you have to encode your videos twice, which takes more computers and more time than just doing it once—there’s another very real cost associated with H.264 video: licensing fees. Remember when I first explained H.264 video (see “H.264” on page 84), and I mentioned: • $2,500 per calendar year per broadcast markets of 100,000–499,999 television households • $5,000 per calendar year per broadcast market of 500,000–999,999 television households • $10,000 per calendar year per broadcast market of 1,000,000 or more television households
* .aspx.
90 | Chapter 5: Video on the Web
Download from Library of Wow! eBook <>
[...] With all the issues around “free” television, why should someone involved in nonbroadcast delivery care? As I mentioned before, the participation fees apply to any delivery of content. After defining that “free” television meant more than just [over-theair], free Internet streaming would be extended through December 31, 2015. And after that...who knows?
Encoding Ogg Video with Firefogg  the).
Encoding Ogg Video with Firefogg | 91
Download from Library of Wow! eBook <>
Figure 5-1. Firefogg home page
Figure 5-2. Allow Firefogg to install
92 | Chapter 5:â€‚Video on the Web
Download from Library of Wow! eBook <>
Figure 5-3. Install Firefogg
Figure 5-4. Restart Firefox
Encoding Ogg Video with Firefogg | 93
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>
Figure 5-5. Installation successful
Download from Library of Wow! eBook <>
Figure 5-6. Let’s make some video!
94 | Chapter 5: Video on the Web
Download from Library of Wow! eBook <>
Figure 5-7. Select your video file
The main Firefogg interface has six “tabs” (shown in Figure 5-8): Presets The default preset is “web video,” which is fine for our purposes. Encoding range Encoding video can take a long time. When you’re first getting started, you may want to encode just part of your video (say, the first 30 seconds) until you find a combination of settings you like. Basic quality and resolution control This is where most of the important options are. Metadata I won’t cover it here, but you can add metadata like title and author to your encoded video. You’ve probably added metadata to your music collection with iTunes or some other music manager. This is the same idea. Advanced video encoding controls Don’t mess with these unless you know what you’re doing. (Firefogg offers interactive help on most of these options. Click the “i” symbol next to each option to learn more about it.) Advanced audio encoding controls Again, don’t mess with these unless you know what you’re doing.
Encoding Ogg Video with Firefogg | 95
Download from Library of Wow! eBook <>
Figure 5-8. Let’s encode a video
We’re only going to look at the “Basic quality and resolution control” tab (Figure 5-9), which contains all the important options: Video Quality This is measured on a scale of 0 (lowest quality) to 10 (highest quality). Higher numbers mean bigger file sizes, so you’ll need to experiment to determine the best size/quality ratio for your needs. Audio Quality This is measured on a scale of –1 (lowest quality) to 10 (highest quality). Higher numbers mean bigger file sizes, just like with the video quality setting. Video Codec This should always be “theora.” Audio Codec This should always be “vorbis.” Video Width and Video Height These default to the actual width and height of your source video. If you want to resize the video during encoding, you can change the width or height here. Firefogg will automatically adjust the other dimension to maintain the original proportions, so your video won’t end up smooshed or stretched. In Figure 5-10, I resize the video to half its original width. Notice how Firefogg automatically adjusts the height to match. 96 | Chapter 5: Video on the Web
Download from Library of Wow! eBook <>
Figure 5-9. Basic quality and resolution control
Figure 5-10. Adjust video width and height
Encoding Ogg Video with Firefogg | 97
Download from Library of Wow! eBook <>
Once you’ve fiddled with all the knobs, click “Save Ogg” to start the actual encoding process (Figure 5-11). Firefogg will prompt you for a filename for the encoded video.
Figure 5-11. Start the encoding process by clicking “Save Ogg”
Firefogg will show a nice progress bar as it encodes your video (Figure 5-12). All you need to do is wait (and wait, and wait)!
Batch Encoding Ogg Video with ffmpeg2theora .) There are a number of offline encoders for Ogg video. If you’re looking at batch encoding a lot of video files and you want to automate the process, you should definitely check out ffmpeg2theora. ffmpeg2theora is an open source, GPL-licensed application for encoding Ogg video. Prebuilt binaries are available for Mac OS X, Windows, and modern Linux distribu tions. It can take virtually any video file as input, including the DV video produced by many consumer-level camcorders. To use ffmpeg2theora, you need to call it from the command line. (On Windows, go to Start Menu→Programs→Accessories→Command Prompt. On Mac OS X, open Applications→Utilities→Terminal.) 98 | Chapter 5: Video on the Web
Download from Library of Wow! eBook <>
Figure 5-12. Encoding in progress
ffmpeg2theora can take a large number of command-line flags. (Type ffmpeg2theora -help to read about them all.) I’ll focus on just three of them: • --video-quality Q, where Q is a number from 0–10. • --audio-quality Q, where Q is a number from –2–10. • - × 480 pixel video with --max_size 320x240 will produce a video that is 320 pixels wide and 213 pixels high. Thus, here is how you could encode a video with the same settings as we used in the previous section (“Encoding Ogg Video with Firefogg” on page 91): you@localhost$ ffmpeg2theora --videoquality 5 --audioquality 1 --max_size 320x240 pr6.dv
The encoded video will be saved in the same directory as the original video, with an .ogv extension added. You can specify a different location and/or filename by passing an --output=/path/to/encoded/video command-line flag to ffmpeg2theora.
Batch Encoding Ogg Video with ffmpeg2theora | 99
Download from Library of Wow! eBook <>
Encoding H.264 Video with HandBrake  (see “Licensing Issues with H.264 Video” on page 90), the easiest way to encode H.264 video is using HandBrake. HandBrake is an open source, GPLlicensed application for encoding H.264 video. (It used to do other video formats too, but in the latest version the developers have dropped support for most other formats and focused all their efforts on H.264 video.) Prebuilt binaries are available for Win dows, (Figure 5-13). Click “Source” and choose “Video File” from the drop-down menu to select a file. HandBrake can take virtually any video file as input, including DV video produced by many consumer-level camcorders.
Figure 5-13. Select your source video
100 | Chapter 5: Video on the Web
Download from Library of Wow! eBook <>
HandBrake will complain that you haven’t set a default directory to save your encoded videos (Figure 5-14). You can safely ignore this warning, or you can open the options window (under the “Tools” menu) and set a default output directory.
Figure 5-14. Ignore this warning
On the righthand side is a list of presets. Selecting the “iPhone & iPod Touch” preset, as in Figure 5-15, will set most of the options you need. One important option that is off by default is the “Web optimized” option. Selecting this option, as shown in Figure 5-16,. In the “Picture” tab, you can set the maximum width and height of the encoded video (Figure 5-17). You should also select the “Keep Aspect Ratio” option to ensure that HandBrake doesn’t smoosh or stretch your video while resizing it.
Encoding H.264 Video with HandBrake | 101
Download from Library of Wow! eBook <>
Figure 5-15. Select the iPhone preset
Figure 5-16. Always optimize for Web
102 | Chapter 5:â€‚Video on the Web
Download from Library of Wow! eBook <>
Figure 5-17. Set width and height
In the “Video” tab, shown in Figure 5-18, you can set several important options: Video Codec Make sure this is “H.264 (x264)”. 2-Pass Encoding If this is checked, HandBrake will run the video encoder twice. The first time, it just analyzes the video, looking for things like color composition, motion, and scene breaks. The second time, it actually encodes the video using the information it learned during the first pass. As you might expect, this takes about twice as long as single-pass encoding, but it results in better video without increasing file size. I always enable two-pass encoding for H.264 video. Unless you’re building the next YouTube and encoding videos 24 hours a day, you should probably use two-pass encoding too. Turbo First Pass When you’ve enabled two-pass encoding, you can get a little bit of time back by enabling this option. It reduces the amount of work done in the first pass (analyzing the video), while only slightly degrading quality. I usually enable this option, but if quality is of the utmost importance to you, you should leave it disabled. Quality There are several different ways to specify the “quality” of your encoded video. You can set a target file size, and HandBrake will do its best to ensure that your encoded video is not larger than that. You can set an average “bitrate,” which is Encoding H.264 Video with HandBrake | 103
Download from Library of Wow! eBook <>
quite literally the number of bits required to store one second’s worth of encoded video. (It’s called an “average” bitrate because some seconds will require more bits than others.) Or you can specify a constant quality, on a scale of 0 to 100 percent. Higher numbers will result in better quality but larger files. There is no single right answer for what quality setting you should use.
Ask Professor Markup Q:.
Figure 5-18. Video quality options
104 | Chapter 5: Video on the Web
Download from Library of Wow! eBook <>
In this example, I’ve chosen an average bitrate of 600 kbps, which is quite high for a 320×240 encoded video. I’ve also enabled two-pass encoding with a “turbo” first pass. In the “Audio” tab, shown in Figure 5-19,.
Figure 5-19. Audio quality options
Next, click the “Browse” button and choose a directory and filename to save your encoded video (Figure 5-20). Finally, click “Start” to start encoding (Figure 5-21). HandBrake will display some progress statistics while it encodes your video (Figure 5-22).
Encoding H.264 Video with HandBrake | 105
Download from Library of Wow! eBook <>
Figure 5-20. Set destination filename
Figure 5-21. Let’s make some video!
106 | Chapter 5: Video on the Web
Download from Library of Wow! eBook <>
Figure 5-22. Patience, grasshopper
Batch Encoding H.264 Video with HandBrake .) As I mentioned in the preceding section, HandBrake also comes in a command-line edition. As with the graphical edition, you should download a recent snapshot from. Like ffmpeg2theora (see “Batch Encoding Ogg Video with ffmpeg2theora” on page 98), the command-line edition of HandBrake offers a dizzying array of options. (Type HandBrakeCLI --help in a Terminal window or at a command prompt to read about them.) I’ll focus on just a few: • --preset "X", where "X" is the name of a HandBrake preset (it’s important to put the name in quotes). The preset you want for H.264 web video is called “iPhone & iPod Touch”. • --width W, where W is the width of your encoded video. HandBrake will automatically adjust the height to maintain the original video’s proportions. • --vb Q, where Q is the average bitrate (measured in kilobits per second). • --two-pass, which enables two-pass encoding. • --turbo, which enables a turbo first pass during two-pass encoding. • --input F, where F is the filename of your source video. • -
Batch Encoding H.264 Video with HandBrake | 107
Download from Library of Wow! eBook <>
From top to bottom, this command runs HandBrake with the “iPhone & iPod Touch” preset, resizes the video to 320 × 240, sets the average bitrate to 600 kbps, enables twopass encoding with a turbo first pass, reads the file pr6.dv, and encodes it as pr6.mp4. Whew!
Encoding WebM Video with ffmpeg I’m writing this on May 20, 2010. The WebM format was literally released yesterday. As such, there is not a lot of choice for encoding tools, and very few end-to-end guides are available. This will all get easier as tools are written (or updated) to provide oneclick support for WebM. Until then, here are the tools you will need: • libvp8, and a special version of ffmpeg with additional patches (to connect it with libvp8) that are not yet part of the official ffmpeg repository: — Instructions for Linux, which I have personally tested on Ubuntu “Lucid” 10.04. — Instructions for Windows, which I have not personally tested. • The latest version of mkclean. Ready? OK.vpx-vp8
If you don’t see the magic words --enable-libvpx-vp8, you don’t have the right version of ffmpeg. (If you swear you just compiled it properly, check to see if you have two versions installed. That’s fine, they won’t conflict with each other—you’ll just need to use the full path of the VP8-enabled version of ffmpeg.) I’m going to show you how to do a two-pass encode (see “Encoding H.264 Video with HandBrake” on page 100). The first pass just scans through the input video file (-i pr6.dv) and writes out some statistics to a logfile (which will be autonamed pr6.dv-0.log). You specify the video codec with the -vcodec parameter: you@localhost$ ffmpeg -pass -an -f rawvideo -y NUL
108 | Chapter 5: Video on the Web
Download from Library of Wow! eBook <>
Most of the ffmpeg command line has nothing to do with VP8 or WebM. libvp8 does support a number of VP8-specific options that you can pass to ffmpeg, but I don’t yet know how any of them work. Once I find a good explanation of these options, I’ll provide a link on this book’s website. For the second pass, ffmpeg will read the statistics it wrote during the first pass and actually do the encoding of the video and the audio. It will write out an MKV file, which we will convert to a WebM file later. (Eventually ffmpeg will be able to write WebM files directly, but that functionality is currently broken in a subtle and pernicious way.) Here’s the command line for the second pass: 614400 -s 320x240 -aspect 4:3 -acodec vorbis -y pr6.mkv
There are five important parameters here: -vcodec libvpx_vp8
Specifies that we’re encoding with the VP8 video codec. WebM always uses VP8 video. -b 614400
Specifies the bitrate. Unlike other formats, libvp8 expects the bitrate in actual bits, not kilobits. If you want a 600-kbps video, multiply 600 by 1024 to get 614400. -s 320x240
Specifies the target size, width by height. -aspect 4:3
Specifies the aspect ratio of the video. Standard-definition video is usually 4:3, but most high-definition video is 16:9 or 16:10. In my testing, I found that I had to specify this explicitly on the command line, instead of relying on ffmpeg to autodetect it. -acodec vorbis
Specifies that we’re encoding with the Vorbis audio codec. WebM always uses Vorbis audio. Now we have an MKV file with VP8 video and Vorbis audio. That’s really close to what we want. The container format of WebM is technically very similar to MKV. In fact, it’s a proper subset. We only need to twiddle a few bits to create our final WebM video file, using the mkclean utility I mentioned earlier: you@localhost$ mkclean --doctype 4 pr6.mkv pr6.webm
And that’s all she wrote!
Encoding WebM Video with ffmpeg | 109
Download from Library of Wow! eBook <> Time.>
110 | Chapter 5: Video on the Web
Download from Library of Wow! eBook <>
The autoplay attribute does exactly what it sounds like: it tells the browser that you would like it to start downloading the video file as soon as the page loads, and autoplay) that allows you: // // // // // //
==UserScript== @name @namespace @description @include ==/UserScript==
Disable video autoplay Ensures that HTML5 video elements do not autoplay *
Download from Library of Wow! eBook <>
waste of bandwidth, though. You’ll save a lot of network traffic if you tell the browser up front about each video. You do this with the type attribute on the <source> element. Here’s the whole thing:  Codecs” on page 85). codecs value itself has to include quotation marks, which means you’ll need to use a different kind of quotation mark to surround the entire type value: <source src="pr6.ogv" type='video/ogg; codecs="theora, vorbis"'>
The <source> element for the WebM file <source> element for the H.264 file is even more complicated. Remember when I said that both H.264 video (see “H.264” on page 84) and AAC audio (see “Advanced Audio Coding” on page 87) be able the type attribute values from this example. Otherwise, you’ll need to work out the type parameters for yourself.
112 | Chapter 5: Video on the Web
Download from Library of Wow! eBook <>
Professor Markup Says At the time of writing (May 20, 2010), the iPad has a bug that prevents it from noticing anything but the first video source listed. Sadly, this means you will need to list your MP4 file first, followed by the free video formats. Sigh.
MIME Types Rear Their Ugly Head There are so many pieces to the video puzzle, I hesitate to even bring this up. But it’s important, because a misconfigured web server can lead to endless frustration as you try to debug why your videos play on your local computer but fail to play when you deploy them to your production site. If you run into this problem, the root cause is probably MIME types. I mentioned MIME types in Chapter 1 (see “MIME Types” on page 1), but you probably glazed over that and didn’t appreciate the significance. So here it is in all-caps.
Professor Markup Shouts VIDEO FILES MUST BE SERVED WITH THE PROPER MIME TYPE!
What’s the proper MIME type? You’ve already seen it; it’s part of the value of the type attribute Add Type directives in your site-wide httpd.conf or in an .htaccess file in the directory where you store your video files. (If you use some other web server, consult your server’s documentation on how to set the Content-Type HTTP header for specific file types.) The AddType directives you’ll need to include are: these once, and forget them. If you don’t, your videos will fail to play in some browsers, even if you include the MIME type in the type attribute in your HTML markup. For even more gory details about configuring your web server, I direct your attention to an excellent Mozilla Developer Center article, “Configuring servers for Ogg me dia”. (The advice in that article applies to MP4 and WebM video, too.) At Last, the Markup | 113
Download from Library of Wow! eBook <>
What About IE? As I write this, Microsoft has released a “developer preview” of Internet Explorer 9. It does not yet support the HTML5 <video> element, but Microsoft has publicly prom ised that the final version of IE 9 will support H.264 video and AAC audio in an MPEG-4 container, just like Safari on desktop Macs and Mobile Safari on iOS. But what about older versions of Internet Explorer? Like, you know, all shipping versions up to and including IE 8? Most people who use Internet Explorer also have the Adobe Flash plug-in installed. Modern versions of Adobe Flash (starting with 9.0.60.184) support H.264 video and AAC audio in an MPEG-4 container. Once you’ve encoded your H.264 video for Safari (see “Encoding H.264 Video with HandBrake” on page 100), you can play it in a Flash-based video player if you detect that your visitor doesn’t have an HTML5-capable browser. FlowPlayer is an open source, GPL-licensed, Flash-based video player. (Commercial licenses are also available; see.) at the Video for Everybody! site.
A Complete Example Let’s look at an example that uses these techniques. I’ve extended the Video for Everybody! code to include a WebM-formatted video. Using these commands, I encoded the same source video into three formats: ## -token_partitions 4 -altref 1 -lag 16 -keyint_min 0 -g 250 -mb_static_threshold 0
114 | Chapter 5: Video on the Web
Download from Library of Wow! eBook <>
-skip_threshold 0 -qmin 1 -qmax 51 -i pr6.dv -vcodec libvpx_vp8 -an -f rawvideo -y NULffmpeg --videobitrate 200 204800 -s 320x240 -aspect 4:3 -acodec vorbis -ac 2 -y pr6.mkv you@localhost$ mkclean --doctype 4 pr6.mkv pr6.webm
The final markup uses a <video> element for HTML5 video, with a nested <object> element for Flash fallback: <video id="movie" width="320" height="240" preload>
With the combination of HTML5 and Flash, you should be able to watch this video in almost any browser and device.
Further Reading • • • • • • • • •
“The <video> element” in the HTML5 specification Video for Everybody! “A gentle introduction to video encoding” “Theora 1.1 is released—what you need to know”, by Christopher Blizzard “Configuring servers for Ogg media” “Encoding with the x264 codec” “Video type parameters” Zencoder Video JS, custom controls for HTML5 video “Everything you need to know about HTML5 audio and video”, by Simon Pieters
Further Reading | 115
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>
CHAPTER 6
You Are Here (And So Is Everybody Else)
Diving In: Geolocation sounds scary. Can I turn it off? A: Privacy is an obvious concern when you’re talking about sharing your physical location with a remote web server. The geolocation API explicitly states: “User Agents must not send location information to websites without the express permission of the user.” In other words, if you don’t want to share your location, you don’t have to.
The Geolocation API The geolocation API lets you share your location with trusted websites. The latitude and longitude are available to JavaScript on the page, which in turn can send that information back to the remote web server and do fancy location-aware things like finding local businesses or showing your location on a map. As you can see from Table 6-1, the geolocation API is supported in several major browsers on desktops and mobile devices. Additionally, some older browsers and devices can be supported by wrapper libraries, as we’ll see later in this chapter.
117
Download from Library of Wow! eBook <>
Table 6-1. Geolocation API support IE
Firefox
Safari
Chrome
Opera
iPhone
Android
·
3.5+
5.0+
5.0+
·
3.0+
2.0+
Along with support for the standard geolocation API, there are a plethora of devicespecific APIs on other mobile platforms. I’ll cover all that later in this chapter.
Show Me the Code The geolocation API centers around a new property on the global navigator object: navigator.geolocation. The simplest use of the geolocation API looks like this: function get_location() { navigator.geolocation.getCurrentPosition(show_map); }
There’s no detection, no error handling, and no options. Your web application should probably include at least the first two of those. To detect support for the geolocation API (see “Geolocation” on page 24), you can use Modernizr: function get_location() { if (Modernizr.geolocation) { navigator.geolocation.getCurrentPosition(show_map); } else { // no native support; maybe try Gears? } }
What you do without geolocation support is up to you. I’ll explain the Gears fallback option in a minute, but first I want to talk about what happens during that call to getCurrentPosition(). As I mentioned at the start Figure 6-1.
Figure 6-1. Geolocation infobar
118 | Chapter 6: You Are Here (And So Is Everybody Else)
Download from Library of Wow! eBook <>
There’s a lot going on here. As the end user, you: • Are told that a website wants to know your location • Are told which website wants to know your location • Can click through to Mozilla’s “Location-Aware Browsing” help page, which explains what the heck is going on • Can choose to share your location • Can choose not to share your location • Can tell your browser to remember your choice (share or don’t share) so you never see this infobar again on this website Furthermore, this infobar is: • Nonmodal, so it won’t prevent you from switching to another browser window or tab • Tab-specific, so it will disappear if you switch to another browser window or tab and reappear when you switch back to the original tab • Unconditional, so there is no way for a website to bypass it • Blocking, so there is no chance that the website can determine your location while it’s waiting for your answer You just saw the JavaScript code that causes this infobar to appear. It’s a single function call that takes a callback function (which I called show_map()). The call to getCurrent Position() her location, devices with dedicated GPS hardware may take some more time to connect to a GPS satellite, and so on.) The coords object has properties like latitude and longitude that represent exactly what they sound like: the user’s physical location in the world. The position object’s properties are listed in Table 6-2.
Download from Library of Wow! eBook <> Show Me the Code | 119
Download from Library of Wow! eBook <>
Table 6-2. Properties of the position object Property
Type
Notes
coords.latitude
double
Decimal degrees
coords.longitude
double
Decimal degrees
coords.altitude
double or null
Meters above the reference ellipsoid
coords.accuracy
double
Meters
coords.altitudeAccuracy
double or null
Meters
coords.heading
double or null
Degrees clockwise from true north
coords.speed
double or null
Meters/second
timestamp
DOMTimeStamp
Like a Date() object
Only three of the properties are guaranteed to be there (coords.latitude, coords.longitude, and coords.accuracy). The rest might come back as null, depending on the capabilities of your device and the backend positioning server with which it communicates. The heading and speed properties are calculated based on the user’s previous position, if possible.
Handling Errors Geolocation is complicated. So many. It has the properties listed in Table 6-3. Table 6-3. Properties of the PositionError object Property
Type
Notes
code
short
An enumerated value
DOMString
Not intended for end users
The code property will be one of the following: • PERMISSION_DENIED (1) if the user clicks the “Don’t Share” button or otherwise denies you access to his location. • POSITION_UNAVAILABLE (2) if the network is down or the positioning satellites can’t be contacted.
120 | Chapter 6: You Are Here (And So Is Everybody Else)
Download from Library of Wow! eBook <>
• TIMEOUT (3) if the network is up but it takes too long to calculate the user’s position. How long is “too long”? I’ll show you how to define that in the next section. • UNKNOWN_ERROR (0) if anything else goes wrong. For example: function handle_error(err) { if (err.code == 1) { // user said no! } }
Ask Professor Markup Q:.
Choices! I Demand Choices!, this “rough idea” could be accurate to as little as one city block or as much as a kilometer in every direction. The second method actually uses dedicated GPS hardware on your device to talk to dedicated GPS positioning satellites that are orbiting the Earth. GPS can usually pinpoint your location to within a few meters. The downside is that the dedicated GPS chip on your device draws a lot of power, so phones and other general-purpose mobile devices usually turn off the chip until it’s needed. That means there will be a startup delay while the chip initializes. For example, if you’re looking for nearby movie listings, a “lowChoices! I Demand Choices! | 121
Download from Library of Wow! eBook <>
accuracy” location is probably good enough. There aren’t that many movie theaters around, even in dense cities, and you’ll probably be listing several of them anyway. On the other hand, if you’re giving turn-by-turn directions in real time, you really do need to know exactly where the user is so you can say “turn right in 20 meters” or whatever. The getCurrentPosition() function takes an optional third argument, a PositionOp tions object. There are three properties you can set in a PositionOptions object (see Table 6-4). All the properties are optional; you can set any, all, or none of them. Table 6-4. PositionOptions object properties Property
Type
Default
Notes
enableHighAccuracy
boolean
false
true might be slower
timeout
long
(no default)
In milliseconds
maximumAge
long
0
In milliseconds
The enableHighAccuracy property is exactly what it sounds like. If it’s set to true, and the device can support it, and the user consents to sharing her exact location, the device will try to provide it. Both iPhones and Android phones have separate permissions for low- and high-accuracy positioning, so it is possible that calling getCurrentPosi tion() with enableHighAccuracy:true will fail, but calling it with enableHighAccur acy:false will succeed. The timeout property specifies the number of milliseconds your web application is willing to wait for a position. This timer doesn’t start counting down until after the user gives permission to even try to calculate her position. You’re not timing the user; you’re timing the network. The maximumAge property allows the device to answer immediately with a cached position. For example, let’s say you call getCurrentPosition() for the very first time, the user consents, and your success callback function is called with a position that was calculated at exactly 10:00 AM. Then suppose that he was 75 seconds (75000 milliseconds) ago. In this case, the device knows where the user was 60 seconds (60000 milliseconds) ago, because it calculated the location the first time you called getCurrentPosition(). Since this is within the specified window, the device doesn’t bother to recalculate the user’s current location. It just returns exactly the same information it returned the first time: the same latitude and longitude, accuracy, and timestamp (10:00 AM). Before you ask for the user’s location, you should think about just how much accuracy you need and set enableHighAccuracy accordingly. If you will need to find the user’s
122 | Chapter 6: You Are Here (And So Is Everybody Else)
Download from Library of Wow! eBook <>
location more than once, you should think about how old the information can be and still be useful, and set maximumAge accordingly. If you need to find the user’s location continuously, changes, you can call the clearWatch() method and pass it this number, and the device will stop calling your callback function. If you’ve ever used the setInterval() and clearInterval() functions in JavaScript, this works the same way.
What About IE? Internet Explorer does not support the W3C geolocation API that I’ve just described (see “The Geolocation API” on page 117). But don’t despair! Gears is an open source browser plug-in from Google that works on Windows, Mac, Linux, Windows Mobile, and Android platforms. It provides a number of features for older browsers, including a geolocation API. It’s not quite the same as the W3C geolocation API, but it serves the same purpose. While we’re on the subject of legacy platforms, I should point out that there are a number of device-specific geolocation APIs on mobile phone platforms. BlackBerry, Nokia, Palm, and OMTP BONDI all provide their own geolocation APIs. Of course, they all work differently from Gears, which in turn works differently from the W3C geolocation API. Wheeeeee!
geo.js to the Rescue geo.js is an open source, MIT-licensed JavaScript library that smooths over the differences between the W3C geolocation API, the Gears API, and the various APIs provided by mobile platforms. To use it, you’ll need to add two <script> elements at the bottom of your page. (Technically, you could put them anywhere, but putting scripts in your <head> will make your page load more slowly. So don’t do that!)
geo.js to the Rescue | 123
Download from Library of Wow! eBook <>
The first script is gears_init.js, which initializes Gears if it’s installed. The second script is geo.js. You can include them in your page using code like this: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Dive Into HTML 5</title> </head> <body> ... <script src="gears_init.js"></script> <script src="geo.js"></script> </body> </html>: function geo_success(p) { alert("Found you at latitude " + p.coords.latitude + ", longitude " + p.coords.longitude); }
124 | Chapter 6: You Are Here (And So Is Everybody Else)
Download from Library of Wow! eBook <> the location, it calls the second callback function, show_map_error():
A Complete Example | 125
Download from Library of Wow! eBook <>
function show_map_error() { $("#live-geolocation").html('Unable to determine your location.'); }
Further Reading • • • • • • •
W3C geolocation API Gears BlackBerry geolocation API Nokia geolocation API Palm geolocation API OMTP BONDI geolocation API geo.js, the geolocation API wrapper script
126 | Chapter 6: You Are Here (And So Is Everybody Else)
Download from Library of Wow! eBook <>
CHAPTER 7
The Past, Present, and Future of Local Storage for Web Applications
Diving In Persistent local storage is one of the areas where native client applications have traditionally held an advantage over web applications. For native applications, the operating system typically provides an abstraction layer for storing and retrieving applicationspecific • • •
A lot of storage space... on the client... that persists beyond a page refresh... and isn’t transmitted to the server.
127
Download from Library of Wow! eBook <> browser-to-end-allbrowser, or LSOs. Briefly, it allows Flash objects to store up to 100 KB of data per domain. In 2005 Brad Neuberg developed an early prototype of a Flash-to-JavaScript bridge called the AJAX Massive Storage System, or AMASS,. providing additional capabilities in browsers. (We’ve previously discussed Gears in the context of providing a geolocation API in Internet Explorer (see “What About IE?” on page 123). plug-ins and APIs. By 2009, dojox.storage could autodetect  plug-in. Despite heroic efforts to paper over the differences (in dojox.storage), they all expose radically different interfaces, have different storage limitations, and present different user experiences. So this is the
128 | Chapter 7: The Past, Present, and Future of Local Storage for Web Applications
Download from Library of Wow! eBook <> transmitted
Download from Library of Wow! eBook <>
Using HTML5 Storage HTML nonexistent and (lengthâ€“1), the function will return null.
130 | Chapter 7:â€‚The Past, Present, and Future of Local Storage for Web Applications
Download from Library of Wow! eBook <>
Tracking Changes to the HTML5 Storage Area way as trapping any other event. If you prefer to use jQuery or some other JavaScript library to register your event handlers, you can do that with the storage event, too.) Here’s how: useful properties listed in Table 7-2. Table 7-2. StorageEvent object properties
a
The url property was originally called uri. Some browsers shipped with that property before the specification changed. For maximum compatibility, you should check whether the url property exists and, if not, check for the uri property instead..”
Using HTML5 Storage | 131
Download from Library of Wow! eBook <> remember your exact position within the game, including the number of moves you’ve made, the positions; }
132 | Chapter 7: The Past, Present, and Future of Local Storage for Web Applications
Download from Library of Wow! eBook <>coded values, we call a resumeGame() function. Using HTML5 Storage, the resumeGame() function checks whether any"]);
HTML5 Storage in Action | 133
Download from Library of Wow! eBook <> database based on SQLite. This early prototype later influenced the creation of the Web SQL Database specification. Web SQL Database (formerly known as “WebDB”) provides
Download from Library of Wow! eBook <>. The early walk-through of IndexedDB is a good tutorial on how IndexedDB works, giving sideby
Download from Library of Wow! eBook <>
• “Introduction to DOM Storage” on the Mozilla Developer Center. (Note: most of this page is devoted to Firefox’s prototype implementation of a globalStorage object, • • •
Web SQL Database specification “Introducing Web SQL Databases”, by Remy Sharp Web Database demonstration persistence.js, an “asynchronous JavaScript ORM” built on top of Web SQL Database and Gears
IndexedDB: • Indexed Database API specification • “Beyond HTML5: Database APIs and the Road to IndexedDB”, by Arun Ranganathan and Shawn Wilsher • “Firefox 4: An early walk-through of IndexedDB”, by Arun Ranganathan
136 | Chapter 7: The Past, Present, and Future of Local Storage for Web Applications
Download from Library of Wow! eBook <>
CHAPTER 8
Let’s Take This Offline
Diving In What just a list of URLs pointing to HTML, CSS, or JavaScript files, images, or any other kinds of resources that may be present. you try to access the web application without a network connection, synchron
✓
✓
✓
·
✓
✓
Download from Library of Wow! eBook <> 137
Download from Library of Wow! eBook <>
The Cache Manifest An offline web application revolves around a cache manifest file. As I’ve already mentioned,
Download from Library of Wow! eBook <>. However, if your web application spans multiple pages, you should list all of the HTML pages in the manifest file; otherwise, the browser will not know that there are other HTML pages that need to be downloaded and cached.
Network Sections. The Cache Manifest | 139
Download from Library of Wow! eBook <>
Fallback Sectionsipe dia. You couldn’t possibly download the entire site, nor would you want to. But suppose you could make part of it available offline. How would you decide which pages to cache? How about this: every page you ever looked at on a hypothetical offlineenabled Wikipedia would be downloaded and cached. That would include every encyclopedia) contains only one), it will display the cached copy of the page. If your browser doesn’t find the page in the appcache,
Download from Library of Wow! eBook <>
downloaded from the original web address, as long as you have an Internet connection. This is important for an “open-ended” offline web application. Continuing with our example, it means that while you’re browsing this hypothetical offline-enabled Wikipedia successfully, the browser fires one final event, cached. This is your signal that the offline The Flow of Events | 141
Download from Library of Wow! eBook <> successfully, download applications extremely frustrating.
142 | Chapter 8: Let’s Take This Offline
Download from Library of Wow! eBook <>. determines that the manifest file hasn’t changed since that date, it will simply return a 304 (Not Modified) status code. Again, none of this is specific to offline web applications.
Download from Library of Wow! eBook <> after you’ve spent a few hours trying to figure out why your browser won’t notice your updated cache manifest. (And even better, if you wait long enough, it will mysteriously startbased web server, these two lines in your .htaccess file will do the trick: ExpiresActive On ExpiresDefault "access"
This will actually disable caching for every file in that directory and all subdirectories. That’s probably not what you want in production, so you should either qualify this with a <Files> directive so it affects only your cache manifest file, or create a subdirectory you’ve changed one of the resources in the appcache, but it’s still at the same URL on your web server. Here, step 2 of the threeph
Download from Library of Wow! eBook <>
clock.js clock.css
Let’s Build One! Remember the Halma game that we introduced in Chapter 4 (see “A Complete Example”
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>
CHAPTER 9
A Form of Madness
Diving In Everybody knows about web forms, right? Make a <form>, add a few <input type="text"> elements and maybe an <input type="password">, finish it off with an <input type="submit"> button, and you’re done. You don’t know the half of it. HTML5 defines over a dozen new input types that you can use in your forms. And when I say “use,” I mean you can use them right now— without any shims, hacks, or workarounds. Now don’t get too excited; I don’t mean to say that all of these exciting new features are actually supported in every browser. Oh goodness no, I don’t mean that at all. In modern browsers, yes, your forms will kick all kinds of ass. In legacy browsers, your forms will still work, but with less ass kicking. Which is to say, all of these features degrade gracefully in every browser. Even IE 6.
Placeholder Text. You’ve probably seen placeholder text before. For example, Mozilla Firefox 3.5 now includes placeholder text in the location bar that reads “Search Bookmarks and History”, as shown in Figure 9-1.
Figure 9-1. Placeholder text in Firefox’s search box
147
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <> vendors +
✓
✓ocus”
Download from Library of Wow! eBook <>
Professor Markup Says Lots of web pages wait until window.onload fires to set the focus. But the window.onload event doesn’t fire until after all your images have loaded. If your page has a lot of images, such a naive script could potentially re-focus the field after the user has started interacting with another part of your page. (This is why power users hate autofocus scripts.) Echoes dots instead of characters as the user types
Password field
<input type="password">
Drop-down list
<select><option>...
File picker
<input type="file">
Submit button
<input type="submit">
Plain text
<input type="text">
Pops up an “open file” dialog new field types, and for reasons that will become clear in a moment, there is no reason not to start using them. The first of these new input types is for email addresses. It looks like this: <form> <input type="email"> <input type="submit" value="Go"> </form>
I was about to write a sentence that started with “In browsers that don’t support type="email"...,” but I stopped myself. Why? Because I’m not sure what it would mean to say that a browser doesn’t support type="email". All browsers “support” type="email". They may not do anything special with it (you’ll see a few examples of 150 | Chapter 9: A Form of Madness
Download from Library of Wow! eBook <>
special treatment in a moment), but browsers that don’t recognize. You see a text box, you type your email address in the text box, and that’s that. Then along comes HTML5, which defines element, she gets an onscreen keyboard that contains a smaller-thanusual space bar, plus dedicated keys for the @ and . characters, as shown in Figure 9-3. To sum up: there’s no downside to converting all your email address form fields to type="email" immediately. Virtually no one will even notice, except iPhone users, who probably won’t notice either. But the ones who do notice will smile quietly and thank you for making their web experience just a little easier.
Download from Library of Wow! eBook <>
Figure 9-3. Keyboard optimized for entering an email address
Figure 9-4. Keyboard optimized for entering a URL
152 | Chapter 9:â€‚A Form of Madness
Download from Library of Wow! eBook <> type="url" exactly like type="text", so there’s no downside to using it for all your web address–inputting needs.
Numbers As Spinboxes Next up: numbers. Asking for a number is, in many ways, trickier than asking for an email or web address. First of all, numbers are more complicated than you might think. Quick: pick a number. –1? No, I meant a number between 1 and 10. 7½? No, no, not a fraction, silly. π? Now you’re just being irrational. My point is, you don’t often ask for “just a number.” It’s more likely that you’ll ask for a number in a particular range, and you may only want certain kinds of numbers within that range—maybe whole numbers but not fractions or decimals, or something more esoteric like numbers divisible by 10. HTML5 has you covered. Let’s look at an example: <input type="number" min="0" max="10" step="2" value="6">
Let’s take that one attribute at a time (you can follow along with a live example if you like): • • • •
type="number" means that this is a number field. min="0" specifies the minimum acceptable value for this field. max="10" is the maximum acceptable value.
step="2", combined with the min value, defines the acceptable numbers in the range: 0, 2, 4, and so on, up to the max value. • value="6" is the default value. This should look familiar. It’s the same attribute name you’ve always used to specify values for form fields. (I mention it here to drive home the point that HTML5 builds on previous versions of HTML. You don’t need to relearn how to do stuff you’re already doing.)
That’s the markup side of a number field. Keep in mind that all of those attributes are optional. If you have a minimum but no maximum, you can specify a min attribute but no max attribute. The default step value is 1, and you can omit the step attribute unless you need a different step value. If there’s no default value, the value attribute can be an empty string or even omitted altogether.
Numbers As Spinboxes | 153
Download from Library of Wow! eBook <>
But HTML5 doesn’t stop there. For the same low, low price of free, you get these handy JavaScript methods as well: input.stepUp(n)
Increases the field’s value by n input.stepDown(n)
Decreases the field’s value by n input.valueAsNumber
Returns the current value as a floating-point number (the input.value property is always a string) Having trouble visualizing it? Well, the exact interface of a number control is up to your browser, and different browser vendors have implemented support in different ways. On the iPhone, where input is difficult to begin with, the browser once again optimizes the virtual keyboard for numeric input as shown in Figure 9-5.
Figure 9-5. Keyboard optimized for entering a number
In the desktop version of Opera, the same type="number" field is rendered as a “spinbox” control, with little up and down arrows that you can click to change the value (Figure 9-6).
154 | Chapter 9: A Form of Madness
Download from Library of Wow! eBook <>
Figure 9-6. A spinbox
Opera respects the min, max, and step attributes, so you’ll always end up with an acceptable numeric value. If you bump up the value to the maximum, the up arrow in the spinbox is grayed out (Figure 9-7).
Figure 9-7. A spinbox at its maximum value
As with all the other input types I’ve discussed in this chapter, browsers that don’t support type="number" will treat it as type="text". The default value will show up in the field (since it’s stored in the value attribute), but the other attributes, like min and max, will be ignored. You’re free to implement them yourself, or you can reuse one of the many JavaScript frameworks that have already implemented spinbox controls. Just check for the native HTML5 support (see “Input Types” on page 25) first, like this: if (!Modernizr.inputtypes.number) { // no native support for type="number" fields // maybe try Dojo or some other JavaScript framework }
Numbers As Sliders Spinboxes, discussed in the preceding section, are not the only way to represent numeric input. You’ve probably also seen “slider” controls that look like Figure 9-8.
Figure 9-8. A slider
Numbers As Sliders | 155
Download from Library of Wow! eBook <>
You can now have slider controls in your web forms, too. The markup looks eerily similar to that for spinbox controls: <input type="range" min="0" max="10" step="2" value="6">
The available attributes are the same as those for type="number"—min, max, step, value—and they mean the same thing. The only difference is the user interface. Instead of a field for typing, browsers are expected to render type="range" as a slider control. At the time of writing, the latest versions of Safari, Chrome, and Opera all do this. (Sadly, the iPhone renders it as a simple text box. It doesn’t even optimize its onscreen keyboard for numeric input.) All other browsers simply treat the field as type="text", so there’s no reason you can’t start using type="range" immediately.
Date Pickers HTML 4 did not include a date picker control. Various JavaScript frameworks have picked up the slack—for example, Dojo, jQuery UI, YUI, and Closure Library—but of course each of these solutions requires “buying into” the framework on which the date picker is built. HTML5 finally defines a way to include a native date picker control without having to script it yourself. In fact, it defines six: date, month, week, time, date + time, and date + time – timezone. So far, as Table 9-4 illustrates, support is...sparse. Table 9-4. Date picker support Input type
Opera
Every other browser
type="date"
9.0+
•
type="month"
9.0+
•
type="week"
9.0+
•
type="time"
9.0+
•
type="datetime"
9.0+
•
type="datetime-local"
9.0+
•
Figure 9-9 shows how Opera renders an <input type="date">.
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>
Figure 9-12. A week picker
Figure 9-13. A time picker
It’s likely that other browsers will eventually support these input types. In the meantime, just like and friends, make Opera users happy, and wait for other browsers to catch up. Alternatively, you can use <input type="date">,
Download from Library of Wow! eBook <>
Search. Not just Google Search or Yahoo! Search. (Well, those too.) Think of any search box, on any page, on any site. Amazon has a search box. Newegg has a search box. Most blogs have a search box. How are they marked up? <input type="text">, just like every other text box on the Web. the type="search" box, Safari inserts a small “x” button on the right side of the box. Clicking the “x” clears the contents of the field. (Google Chrome, which shares much technology with Safari under the hood, also exhibits this behavior.) Both of these small tweaks are done to match the look and feel of native search boxes in iTunes and other Mac OS X client applications  platform-specific conventions. As with all the other new input types, browsers that don’t recognize type="search" will treat it like type="text", so there is absolutely no reason not to start using type="search" for all your search boxes today. Search Boxes | 159
Download from Library of Wow! eBook <>
Figure 9-16. Opera validates type=“email”
Professor Markup Says Well, there is one reason you might not want to use <input type="search">.
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>
CHAPTER 10
“Distributed,” “Extensibility,” and Other Fancy Words
Diving In There are over 100 elements in HTML5. Some are purely semantic (see Chapter 3), and others are just containers for scripted APIs (see Chapter 4). Throughout the history of HTML (see Chapter 1),  semantics
Download from Library of Wow! eBook <>), (see “The Root Element” on page 33) usually contains two children, <head> (see “The <head> Element” on page 34) and <body>. The <body> element usually contains multiple children, each of which may have child elements of its own. For example, your page might include an <h1> element within an <hgroup> element within a <header> element (see “Headers”ularies within other vocabularies, all by reusing the natural structure of the DOM. (I’ll show multiple examples of nested vocabularies throughout this chapter.) 164 | Chapter 10: “Distributed,” “Extensibility,” and Other Fancy Words
Download from Library of Wow! eBook <>
semantifying isn’t in the DOM, you should step back and reevaluate whether microdata is the right solution. Does Professor Markup’s statement make more sense now? I hope so. Let’s see how this works in action.
The Microdata Data Model Defining your own microdata vocabulary is easy. First you need a namespace, which is just a URL. The namespace URL can: • name (the user’s full name) • photo (a link to a picture of the user) • url (a link to a site associated with the user, like a blog or a Google profile) Two of these properties are URLs, and the other is plain text. Each of them lends itself to a natural form of markup, even before you start thinking about microdata or vocabularies. Imagine that you have a profile page or an “about” page. Your name is probably marked up as a heading, like an <h1> element. Your photo is probably an <img> element, since you want people to see it. And any URLs associated with your profile are probably already marked up as hyperlinks, because you want people to be able to click them. For the sake of discussion, let’s say your entire profile is also wrapped in a <section> element to separate it from the rest of the page content. Thus: . However, there are a handful of exceptions, as Table 10-1 illustrates.
Download from Library of Wow! eBook <> The Microdata Data Model | 165
Download from Library of Wow! eBook <> Table 10-1,>
166 | Chapter 10: “Distributed,” “Extensibility,” and Other Fancy Words
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <> Words
Download from Library of Wow! eBook <>=""> document
Download from Library of Wow! eBook <>
Where’s the microdata property value? It’s already there, in the src attribute. If you recall from Table 10-1, relationships
Download from Library of Wow! eBook <> are one microdata property, and the last 12 characters of this text>
Ta-da! In English, this says: “This person’s title is ‘Developer: street-address, locality, region, postal-code, and country-name. If you’re a programmer, you are probably familiar with dot notation to define objects and their properties. Think of the relationship like this: • • • • • • •
Marking Up People | 171
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>
has a street address and a suite number, they would both go into the street-address sub. This person has another URL at.”
Marking Up People | 173
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <> are no hard,).!
Marking Up People | 175
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>data
Download from Library of Wow! eBook <>, (see Chapter separating out the different parts of a URL. You can’t declare that the first URL query
178 | Chapter 10: “Distributed,” “Extensibility,” and Other Fancy Words
Download from Library of Wow! eBook <>
parameter is the latitude,” very quickly. That is, it’s likely she needs>
Geolocation information is defined in its own vocabulary, like the address of a Person or Organization. Therefore, this <span> element needs three attributes: itemprop="geo"
Says that this element represents the geo property of the surrounding Organization. itemtype=""
Says which microdata vocabulary this element’s properties conform to. itemscope
Says that this element is the enclosing element for a microdata item with its own vocabulary (given in the itemtype attribute). All the properties within this element are properties of the Geo vocabulary (), not the surrounding Organization vocabulary ( tion). The next big question that this example answers is, “How do you annotate invisible data?” You do this with the <meta> element. In previous versions of HTML, you could only use the <meta> element within the <head> of your page (see “The <head> Element” on page 34). In HTML5, you can use the <meta> element anywhere. And that’s exactly what we’re doing here: <meta itemprop="latitude" content="37.4149" />
Marking Up Organizations | 179
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>
All the information about the event is contained within the <article> element, so that’s where we need to put the itemtype and itemscope attributes: <article itemscope
The URL for the Event vocabulary is, which also happens
Download from Library of Wow! eBook <>> elements? Looking back at Table 10-1, the semantics
Download from Library of Wow! eBook <>
"name" is defining a property in the Organization vocabulary, not the Event vocabulary. The <p> element defined the beginning of the scope of the Organization properties, and that <p> element hasn’t yet been closed with (see “Marking Up People” on page 171) and marking up the address of an Organization (see “Marking Up Organizations” on page 177)): <span <span <span <span
itemprop="street-address">5th května 65</span><br>140 21</span>Praha 4</span><br>Czech Republic</span>
There are no more properties of the Address, so we close the <span> element that started the Address scope and pop the stack: </span>
There are also>
Because we’ve closed the <span> that contained the Geo properties, we’re back to defining
Download from Library of Wow! eBook <>
correctly (marking up hyperlinks with <a href>), declaring that the hyperlink is a microdata url property is simply a matter of adding the itemprop attribute: <p> <a itemprop="url" href=""> GDD/Prague home page </a> </p> </article>.
The Return of Google Rich Snippets
184 | Chapter 10: “Distributed,” “Extensibility,” and Other Fancy Words
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>>.
Download from Library of Wow! eBook <> 186 | Chapter 10: “Distributed,” “Extensibility,” and Other Fancy Words
Download from Library of Wow! eBook <>
The first property is simple: itemreviewed is just text, and here it’s contained in an <h1> element, so that’s where we should put the itemprop attribute: <h1 itemprop="itemreviewed">Anna's Pizzeria</h1>>
Download from Library of Wow! eBook <>
< (enhanced
188 | Chapter 10: “Distributed,” “Extensibility,” and Other Fancy Words
Download from Library of Wow! eBook <> • • • • • • •
“About rich snippets and structured data” “People” “Businesses and organizations” “Events” “Reviews” “Review ratings” Google Rich Snippets Testing Tool Google Rich Snippets Tips and Tricks
Further Reading | 189
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>; codecs="vorbis"').replace(/no/, ''));
191
Download from Library of Wow! eBook <>
<audio> in WAV format
var a = document.createElement('audio'); return !!(a.canPlayType && a.canPlayType('audio/wav; codecs="1"').replace(/no/, ''));
<audio> in AAC format
var a = document.createElement('audio'); return !!(a.canPlayType && a.canPlayType('audio/mp4; codecs="mp4a.40.2"').replace(/no/, ''));
<canvas>
See Chapter 4
return !!document.createElement('canvas').getContext;
<canvas> text API
See “Text” on page 63
var c = document.createElement('canvas'); return c.getContext && typeof c.getContext('2d').fillText == 'function';
<command>
return 'type' in document.createElement('command');
<datalist>
return 'options' in document.createElement('datalist');
<details>
return 'open' in document.createElement('details');
<device>
return 'type' in document.createElement('device');
192 | Appendix: The All-in-One Almost-Alphabetical Guide to Detecting Everything
Download from Library of Wow! eBook <>
<form> constraint validation
return 'noValidate' in document.createElement('form');
<iframe sandbox>
return 'sandbox' in document.createElement('iframe');
<iframe srcdoc>
return 'srcdoc' in document.createElement('iframe');
<input autofocus>
See “Autofocus Fields” on page 148
return 'autofocus' in document.createElement('input');
<input placeholder>
See “Placeholder Text” on page 147
return 'placeholder' in document.createElement('input');
<input type="color">
Download from Library of Wow! eBook <>

Download from Library of Wow! eBook <>

Download from Library of Wow! eBook <>

Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>:â€‚The All-in-One Almost-Alphabetical Guide to Detecting Everything
Download from Library of Wow! eBook <>
Web Workers
return !!window.Worker;
Undo
return typeof UndoManager !== 'undefined';
Further Reading Specifications and standards: • • • • • • • •
HTML5 Geolocation Server-Sent Events WebSimpleDB Web Sockets Web SQL Database Web Storage Web Workers
JavaScript libraries: • Modernizr, an HTML5 detection library
Further Reading | 199
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>
Index
A AAC (Advanced Audio Coding), 87 Almost Standards mode, 32 alternate link relation, 37 APIs canvas API, 16–18 canvas text API, 17 ExplorerCanvas, 74 geo.js, 123 geolocation API, 24, 117–120 Indexed Database API, 135 Web Worker, 23 applications local storage, 127–136 offline web applications, 23, 137–146 archives, link relations, 38 article element, 41, 47 aside element, 41 audio codecs about, 85–88 encoding Ogg Vorbis video, 91–99 Audio Video Interleave video container format, 82 authors, link relations, 38 autofocus, web forms, 27, 148 autoplay attribute, 110
B backward compatibility about, 11 XHTML, 12 batch encoding H.264 video codec, 107 Ogg Vorbis video codec, 98
breadcrumbs, link relations, 39 browsers audio video support, 88 autofocus support, 28, 149 canvas support, 16 canvas text support, 17 doctype and modes, 31 error handling, 13 geolocation support, 24 handling unknown elements, 42–45 headers, 1 HTML5 input types, 26 HTML5 support, 15 JavaScript, 23 local storage, 132 microdata support, 29 Microsoft Internet Explorer, 73, 114, 123 Midas, 3 Mosaic, 3 offline support, 24 placeholder support, 27 placeholder text support, 148 SQL database support, 134
C cache manifest, offline web applications, 138– 141, 143 canPlayType() function, 20 canvas about, 16–18 coordinates, 60 drawing text, 63–66 images, 70–73 paths, 61–63 canvas element, 57
We’d like to hear your suggestions for improving our indexes. Send email to index@oreilly.com.
201
Download from Library of Wow! eBook <>
canvas text API, 17 character encoding, 35 codecs about, 20 audio, 85–88, 91–99 video, 83, 90, 100–109 color pickers, web forms, 160 conditional comments, 74 containers, video, 81 Content-Type header, 1 cookies, compared to HTML5 Storage, 21 coordinates, canvas, 60 custom vocabularies, microdata, 164
D date pickers, web forms, 156 dates and times, 49 dd element, 170 debugging offline web applications, 142–144 detecting autofocus support, 28 canvas support, 16 canvas text support, 17 geolocation support, 24 HTML5 input types, 26 HTML5 support, 15 microdata support, 29 offline support, 24 placeholder support, 27 doctype, 31 DOM (Document Object Model) about, 15 detecting canvas support, 16 detecting canvas text support, 17 video, 19, 20 DOM events, 141 drawing, 57–79 canvas coordinates, 60 gradients, 67 Halma game example, 75–79 images, 70–73 paths, 61–63 shapes, 58 text, 63–66
E elements about, 163
article element, 41, 47 aside element, 41 canvas element, 16, 57 dd element, 170 footer element, 41, 52 handling unknown elements, 42–45 head element, 34–40 header element, 41 hgroup element, 41 img element, 2, 8, 70 link relations, 37 mark element, 41 nav element, 41 root element, 33 section element, 41 source element, 112 time element, 41 video element, 18–21 email addresses validating in JavaScript, 160 web forms, 150 error handling about, 11 browsers, 13 geolocation, 120 events DOM events, 141 marking up, 180–185 storage events, 131 examples geo.js, 125 Halma game, 75–79, 132, 145 Video for Everybody!, 114 ExplorerCanvas, 74 external link relations, 38
F fallback section, cache manifest, 140 feed autodiscovery, 37 ffmpeg2theora, 98 fields autofocus, 148 email addresses, 150 Firefogg, 91–98 Flash Video video container format, 82 FlowPlayer, 114 font sizes, 65 footer element, 41 footers, 52
202 | Index
Download from Library of Wow! eBook <>
history prior to HTML5, 128 using, 130–132
formats, video, 19 forms (see web forms)
I
G Gears plug-in, 128 geo.js, 123–125 geolocation, 117–126 about, 24 API, 117–120 error handling, 120 geo.js, 123–125 methods for calculating location, 121 using invisible data, 178 vocabulary, 179 getCurrentPosition() function, 118, 120, 122, 124 Google On2, 85 Rich Snippets, 174, 184 GPS (Global Positioning System), 121 gradients, drawing, 67
H H.264 video codec, 84, 90, 100–108 Halma game example, 75–79, 132, 145 HandBrake, H.264 video codec, 100–108 head element, 34–40 header element, 41 headers about, 45–47 Content-Type, 1 hgroup element, 41 history HTML, 7–11 HTML5, ix local storage prior to HTML5, 128 standards development, 2–7 XHTML, 10 XML, 10 HTML competing visions, 11 development history, 7–11 page structure, 33 HTML Working Group, 9 HTML5 Storage, 127–136 about, 21, 129 future of, 134 Halma game example, 132
IE (Internet Explorer) audio video support, 89 canvas and VML support, 73 geolocation, 123 styling unknown elements, 42 video support, 114 images, displaying, 70–73 img element, 2, 8, 70 Indexed Database API, 135 input types about, 25 web forms, 147 iPhone, web forms, 151
J JavaScript autofocus, 27 running in background, 23
L language, 34 libraries, Modernizr, 16 license link relation, 39 licensing, H.264 video codec, 90 link relations, 36–40 local storage (see HTML5 Storage) LSOs (Local Shared Objects), 128
M mailing address format, 172 mark element, 41 microdata about, 28, 164 data mode, 165–168 Microsoft Internet Explorer audio video support, 89 canvas and VML support, 73 geolocation, 123 styling unknown elements, 42 video support, 114 Midas browser, 3 MIME types about, 1 Index | 203
Download from Library of Wow! eBook <>
importance of, 10 video, 113 XHTML, 9, 10 Modernizr, 16 Mosaic browser, 3 MP3 (MPEG-1 Audio Layer 3), 86 MPEG-4 video container format, 82
R
N
scoping, microdata, 164 scripting, 11 search boxes, web forms, 158 search link relation, 40 section element, 41 shapes, drawing, 58 sidebar link relation, 40 sliders, numbers as, 155 source element, 112 spinboxes, numbers as, 153 SQL database support, 134 standards HTML history, 7–9 implementations and specifications, 1 process of creating, 2–7 Standards mode, 32 storage (see HTML5 Storage) StorageEvent objects, 131 stylesheet link relation, 37
namespaces microdata, 165 need for, 33 nav element, 41 navigation about, 51 breadcrumbs, 39 network section, cache manifest, 139 nofollow link relation, 39 noreferrer link relation, 39 numbers, web forms, 153–156
O objects, DOM, 15 offline web applications, 137–146 about, 23 cache manifest, 138–141 debugging, 142–144 flow of events, 141 Halma game example, 145 Ogg video container format, 82 Ogg Vorbis audio codec, 87, 91–99 organizations, marking up, 176–180
P paths about, 145 canvas, 61–63 people, marking up, 168–175 pingback link relation, 39 placeholder text about, 27 web forms, 147 prefetch link relation, 40 preload attribute, 110 publication date, 49
Q
relative font sizes, 65 reviews, marking up, 185–189 Rich Snippets, 174, 184 root element, 33
S
T tag link relation, 40 tag-sets, XML, 9 text canvas text API, 17 character encoding, 35 drawing, 63–66 placeholder text, 27, 147 Theora video codec, 84 time element, 41 times and dates, 49 tracking changes in HTML5 storage area, 131 translations, linking, 38
U URLs microdata, 166 Person vocabulary, 173 web forms, 151
Quirks mode, 32 204 | Index
Download from Library of Wow! eBook <>
World Wide Web Consortium (see W3C)
V validating email addresses in JavaScript, 160 video, 81–115 about, 18–21 audio codecs, 85–88, 91–99 browser support, 88 containers, 81 markup, 110–113 Microsoft Internet Explorer, 114 video codecs, 83, 90, 100–109 Video for Everybody! example, 114 Vorbis audio codec, 87, 91–99 VP8 video codec, 85
X XForms, backward compatibility, 12 XHTML about, 10 backward compatibility, 12 development history, 9 XML development history, 10 tag-sets, 9
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>aucas protection from the European Union. In contrast, the New Zealand Department of Conservation encourages the hunting of alpine chamois, hoping to limit the animal’s impact on native flora. The cover image is from J. G. Wood’s Animate Creation. The cover font is Adobe ITC Garamond. The text font is Linotype Birka; the heading font is Adobe Myriad Condensed; and the code font is LucasFont’s TheSansMonoCondensed.
Download from Library of Wow! eBook <>
Download from Library of Wow! eBook <>