www.it-ebooks.info www.it-ebooks.info HTML5 The book that should have been in the box ® Matthew MacDonald Beijing | Cambridge | Farnham | Köln | Sebastopol | Tokyo www.it-ebooks.info HTML5: The Missing Manual by Matthew MacDonald Copyright © 2011 Matthew MacDonald All rights reserved Printed in the Unites States of America Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472 O’Reilly Media books may be purchased for educational, business, or sales promotional use Online editions are also available for most titles: http://my.safaribooksonline.com For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com Printing History: August 2011: First Edition Nutshell Handbook, the Nutshell Handbook logo, the O’Reilly logo, and “The book that should have been in the box” are registered trademarks of O’Reilly Media, Inc HTML5: The Missing Manual, The Missing Manual logo, Pogue Press, and the Pogue Press logo are trademarks of O’Reilly Media, Inc Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and O’Reilly Media, Inc was aware of a trademark claim, the designations have been printed in caps or initial caps While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein ISBN: 978-1-449-30239-9 [M] www.it-ebooks.info Table of Contents The Missing Credits xi Introduction Part One: Meet the New Language Chapter 1: Introducing HTML5 11 The Story of HTML5 XHTML 1.0: Getting Strict XHTML 2: The Unexpected Failure HTML5: Back From the Dead HTML: The Living Language Three Key Principles of HTML5 Don’t Break the Web Pave the Cowpaths Be Practical Your First Look at HTML5 Markup The HTML5 Doctype Character Encoding The Language Adding a Style Sheet Adding JavaScript The Final Product A Closer Look at HTML5 Syntax The Loosened Rules HTML5 Validation The Return of XHTML 11 12 12 13 14 15 15 17 17 18 20 21 21 22 22 23 24 24 25 27 iii www.it-ebooks.info HTML5’s Element Family Added Elements Removed Elements Adapted Elements Tweaked Elements Standardized Elements Using HTML5 Today Evaluating Browser Support Browser Adoption Statistics Feature Detection with Modernizr Feature “Filling” with Polyfills 29 29 30 30 32 33 34 34 36 38 40 Chapter 2: A New Way to Structure Pages 43 Introducing the Semantic Elements Retrofitting a Traditional HTML Page Page Structure the Old Way Page Structure with HTML5 Subtitles with Adding a Figure with Adding a Sidebar with Browser Compatibility for the Semantic Elements Designing a Site with the Semantic Elements Deeper into Headers Navigation Links with Deeper into Footers Deeper into Sections The HTML5 Outlining System How to View an Outline Basic Outlines Sectioning Elements Solving an Outline Problem 44 45 47 49 52 53 56 57 60 61 62 67 69 70 70 71 73 76 Chapter 3: Meaningful Markup 81 The Semantic Elements Revisited Dates and Times with JavaScript Calculations with Highlighted Text with Other Standards that Boost Semantics ARIA (Accessible Rich Internet Applications) RDFa (Resource Description Framework) Microformats Microdata Google Rich Snippets Enhanced Search Results The Recipe Search Engine iv table of contents www.it-ebooks.info 82 83 84 86 87 88 89 89 95 97 98 101 Part Two: Creating Modern Web Pages Chapter 4: Web Forms, Refined 107 Understanding Forms Revamping a Traditional HTML Form Adding Hints with Placeholders Focus: Starting in the Right Spot Validation: Stopping Errors How HTML5 Validation Works Turning Validation Off Validation Styling Hooks Validating with Regular Expressions Custom Validation Browser Support for Validation New Types of Input Email Addresses URLs Search Boxes Telephone Numbers Numbers Sliders Dates and Times Colors New Elements Input Suggestions with Progress Bars and Meters Toolbars and Menus with and An HTML Editor in a Web Page Using contentEditable to Edit an Element Using designMode to Edit a Page 108 109 113 115 116 116 118 119 120 121 123 125 128 128 128 129 129 130 131 132 132 133 135 138 138 138 141 Chapter 5: Audio and Video 143 Understanding Video Today Introducing HTML5 Audio and Video Making Some Noise with Getting the Big Picture with Format Wars and Fallbacks Meet the Formats Browser Support for Media Formats Multiple Formats: How to Please Every Browser The Element The Flash Fallback Controlling Your Player with JavaScript Adding Sound Effects Creating a Custom Video Player JavaScript Media Players Captions and Accessibility 144 145 145 148 149 150 152 154 154 155 160 160 163 166 168 table of contents www.it-ebooks.info v Chapter 6: Basic Drawing with the Canvas 171 Getting Started with the Canvas Straight Lines Paths and Shapes Curved Lines Transforms Transparency Building a Basic Paint Program Preparing to Draw Drawing on the Canvas Saving the Picture in the Canvas Browser Compatibility for the Canvas Polyfilling the Canvas The Canvas Fallback and Feature Detection 172 174 177 179 182 185 188 189 190 192 195 196 197 Chapter 7: Deeper into the Canvas 199 Other Things You Can Draw on the Canvas Drawing Images Slicing, Dicing, and Resizing an Image Drawing Text Shadows and Fancy Fills Adding Shadows Filling Shapes with Patterns Filling Shapes with Gradients Putting It Together: Drawing a Graph Making Your Shapes Interactive Keeping Track of What You’ve Drawn Hit Testing with Coordinates Animating the Canvas A Basic Animation Animating Multiple Objects A Practical Example: the Maze Game Setting Up the Maze Animating the Face Hit Testing with Pixel Colors 200 200 202 203 205 205 207 208 211 216 217 220 222 223 224 229 229 232 234 Chapter 8: Boosting Styles with CSS3 237 Using CSS3 Today Strategy 1: Use What You Can Strategy 2: Treat CSS3 Features as Enhancements Strategy 3: Add Fallbacks with Modernizr Browser-Specific Styles vi table of contents www.it-ebooks.info 238 238 238 240 243 Web Typography Web Font Formats Using a Font Kit Using Google Web Fonts Using Your Own Fonts Putting Text in Multiple Columns Adapting to Different Devices Media Queries More Advanced Media Queries Replacing an Entire Style Sheet Recognizing Mobile Devices Building Better Boxes Transparency Rounded Corners Backgrounds Shadows Gradients Creating Effects with Transitions A Basic Color Transition More Transition Ideas Transforms 244 245 247 250 252 253 255 256 259 261 261 263 263 265 266 268 269 271 272 274 274 Part Three: Building Web Apps with Desktop Smarts Chapter 9: Data Storage 281 Web Storage Basics Storing Data A Practical Example: Storing the Last Position in a Game Browser Support for Web Storage Deeper into Web Storage Removing Items Finding All the Stored Items Storing Numbers and Dates Storing Objects Reacting to Storage Changes Reading Files Getting Hold of a File Browser Support for the File API Reading a Text File Replacing the Standard Upload Control Reading Multiple Files at Once Reading an Image File 282 283 285 287 288 288 288 289 290 292 294 295 295 296 298 298 299 table of contents www.it-ebooks.info vii Chapter 10: Offline Applications 303 Caching Files with a Manifest Creating a Manifest Using Your Manifest Putting Your Manifest on a Web Server Updating the Manifest File Browser Support for Offline Applications Practical Caching Techniques Accessing Uncached Files Adding Fallbacks Checking the Connection Pointing Out Updates with JavaScript 304 305 307 308 310 312 314 314 315 317 318 Chapter 11: Communicating with the Web Server 323 Sending Messages to the Web Server The XMLHttpRequest Object Asking the Web Server a Question Getting New Content Server-Sent Events The Message Format Sending Messages with a Server Script Processing Messages in a Web Page Polling with Server-Side Events Web Sockets Assessing Web Sockets A Simple Web Socket Client Web Socket Examples on the Web 324 325 325 330 333 334 335 337 339 340 341 343 344 Chapter 12: More Cool JavaScript Tricks 347 Geolocation How Geolocation Works Finding a Visitor’s Coordinates Dealing with Errors Setting Geolocation Options Showing a Map Monitoring a Visitor’s Moves Web Workers A Time-Consuming Task Doing Work in the Background Handling Worker Errors Canceling a Background Task Passing More Complex Messages viii table of contents www.it-ebooks.info 348 349 351 353 355 356 360 360 362 364 367 367 368 index Index Symbols (&&) and operator, 409 (==) equal to operator, 409 @fontface feature, 244 (>) greater than operator, 409 (>=) greater than or equal to operator, 409 (=), 409 H HandBrake converter software, 156 hashbang URLs, 373 hCalendar, 94 hCard, 89 element, in HTML5, 19 headers in CSS, 392 designing, using semantic elements, 61 “fat” headers, 53, 61 element, 50, 61, 82 heading structure of a site, 63 , , etc., 52 , formatting example in CSS, 394 height attribute, 148, 172 hexadecimal color code, 132 element description of, 82 subtitles, adding with, 52 highlighting text, 86 hints, adding with placeholders, 113–115 history management browser compatibility for session history, 377 hashbang URLs, 373 the history object, 371 HTML5, session history and, 374–376 the URL problem, 372 URLs, satisfying with extra pages, 378 index www.it-ebooks.info Index hit testing with coordinates, 220 with pixel colors, 232–234 , , etc elements basic outlines and, 71–73 outline problems, solving, 77–79 subtitles and, 52 :hover pseudoclass, 389 element, 31 element, in HTML5, 19 HTML as living language, 14 object properties, common, 415 retrofitting with semantic elements, 45 traditional forms, revamping, 109–112 HTML5 audio and video features not supported in, 145 new elements, 145 browser compatibility browser adoption statistics, 36–38 browser support, 34–36 features overview, 34 Modernizr, feature detection with, 38–40 polyfills, feature filling with, 40 development of, 11–14 elements, changes to, 29–33 good style, summary of, 25 key principles of be practical, 17 don’t break the Web, 15 “pave the cowpath”, 17 major features of, 14 obsolete features, how they are handled, 16 semantic rules in style sheets, example of, 391–396 syntax rules, loosening of, 24 validation, 25–27 HTML editors See editors, HTML HTML forms See forms H.264 video format, 150, 151, 152 I id attribute, 172, 413 id selectors, in CSS, 388 IE See Internet Explorer (IE) image gallery, creating with transforms, 275 images drawing, in the canvas, 200 reading image files, in File API, 299–301 slicing, cropping, and resizing, 202 troubleshooting squashed images, 201 indenting, 19 IndexedDB, 301 inherited values in CSS, 386 inline events, 417 inline function, 417 innerHTML property, 415 input autocomplete attribute, 125 autocorrect and autocapitalize atttributes, 125 element, traditional, 111 multiple attribute, 125 new types of, browser compatibility for, 127 sliders using the range data type, 130 spellcheck attribute, 125 element as attribute selector in CSS3, 390 File API and, 295, 298 form input using colors, 132 dates and times, 131 email addresses, 128 numbers, 129–131 overview of, 125–127 search boxes, 128 telephone numbers, 129 URLs, 128 traditional, 111 in-range and out-of-range pseudoclasses, 119 interactivity, shapes in the canvas, 216–221 Internet Explorer (IE) browser support for HTML5, 37 non-support for placeholder text, 114 web storage, 287 nonsupport for geolocation, 348 recognizing foreign elements, in older versions, 59 troubleshooting code JavaScript errors, identifying, 407 Mark of the Web comment, 23, 59, 399 Internet resources See online resources IP addresses, geolocation and, 349 iPhones and iPads See devices, adapting to (italic) formatting, 31 itemprop attribute, 96 itemscope attribute, 96 itemtype attribute, 96 J JavaScript adding, 22 application updates, pointing out, 318–320 calculations with , 84 the canvas and, 171 checking browser connections with, 317 debuggers, 407 form submission, bypassing, 109 index www.it-ebooks.info 425 Index form validation with, 124 geolocation accuracy of, 353 browser support for, 348 errors, dealing with, 353 how it works, 349–351 how you can use it, 351 maps, showing, 356–359 object literals, understanding, 356 options, setting, 355 visitor coordinates, finding, 351–353 visitors, monitoring the moves of, 360 history management browser compatibility for session history, 377 hashbang URLs, 373 the history object, 371 HTML5, session history and, 374–376 the URL problem, 372 URLs, satisfying with extra pages, 378 how web pages use embedding script in markup, 398 events, responding to, 402–404 functions, using, 400 script files, moving code to, 401 JSON (JavaScript Object Notation) encoding, 291 language essentials arrays, 410 conditional logic, 408 errors, identifying, 407 functions that receive and return data, 411 loops, 410 operations, 407–409 variables, 405 libraries form validation, 124 using Oomph browser plug-in with, 94 media players J W Player, 159 options, 166–168 sound effects, adding, 160–166 page interaction elements, manipulating, 413 events, connecting to dynamically, 415 events, inline, 417 HTML object properties, common, 415 tasks of, 412 web workers background tasks, cancelling, 367 background work, 364–367 complex messages, passing, 368–370 fallback for, 368 functioning of, 360 safety measures, 361 426 for time-consuming tasks, 362–364 ways to use, additional, 371 worker errors, handling, 367 Worker object, 364 Java web socket test server, 345 JSON (JavaScript Object Notation) encoding, 291 K Kaazing web socket test server, 345 key, as data name, 283 L language codes, locating, 21 language information, including, 21 layout property in CSS, 384 LeadIn class, formatting example, 394 less than operator (