HTML5 The Missing Manual 2nd Edition

This book covers HTML5, the latest and greatest version of the HTML standard.


Matthew MacDonald


519 Pages

49539 Reads

66 Downloads

English

PDF Format

22.1 MB

HTML Learning

Download PDF format


  • Matthew MacDonald   
  • 519 Pages   
  • 26 Feb 2015
  • Page - 1

    read more..

  • Page - 2

    read more..

  • Page - 3

    read more..

  • Page - 4

    read more..

  • Page - 5

    read more..

  • Page - 6

    read more..

  • Page - 7

    read more..

  • Page - 8

    read more..

  • Page - 9

    read more..

  • Page - 10

    THE MISSING CREDITS VIII ACKNOWLEDGEMENTS No author could complete a book without a small army of helpful individuals. I’m deeply indebted to the whole Missing Manual team, especially my editor Nan Barber, who never seemed fazed by the shifting sands of HTML5; and expert tech reviewers Shelley Powers and Darrell Heath, who helped spot rogue errors read more..

  • Page - 11

    THE MISSING CREDITS IX iPhone: The Missing Manual, Fifth Edition by David Pogue iPhone App Development: The Missing Manual by Craig Hockenberry iPhoto ’11: The Missing Manual by David Pogue and Lesa Snider iPod: The Missing Manual, Eleventh Edition by J.D. Biersdorfer and David Pogue JavaScript & jQ uery: The Missing Manual, Second Edition read more..

  • Page - 12

    read more..

  • Page - 13

    XI At first glance, you might assume that HTML5 is the fifth version of the HTML web page–writing language. But the real story is a whole lot messier. HTML5 is a rebel. It was dreamt up by a loose group of freethinkers who weren’t in charge of the official HTML standard. It allows page-writing practices that were banned a decade ago. read more..

  • Page - 14

    HTML5: THE MISSING MANUAL, SECOND EDITION XII WHAT YOU NEED TO GET STARTED Despite the challenges HTML5 presents, there’s one fact that no one disputes— HTML5 is the future. Huge software companies like Apple, Google, and Microsoft have lent it support, and the W3C (World Wide Web Consortium) has given up its work on XHTML to formalize read more..

  • Page - 15

    INTRODUCTION XIII WHAT YOU NEED TO GET STARTED • Web page writing. This book assumes you’ve written at least a few web pages before (or at the very least, you understand how to use HTML elements to struc- ture content into headings, paragraphs, and lists). If you’re new to web design, you’re better off with a gentler introduction, read more..

  • Page - 16

    HTML5: THE MISSING MANUAL, SECOND EDITION XIV WHEN WILL HTML5 BE READY? Currently, no browser supports every last detail of HTML5, in part because HTML5 is really a collection of interrelated standards. Google Chrome generally leads the browser race in HTML5 support, with Firefox and Opera in close pursuit. Safari lags the pack a bit, and read more..

  • Page - 17

    INTRODUCTION XV ABOUT THE OUTLINE FREQUENTLY ASKED QUESTION The Difference Between HTML5 and HTML 5.1 Is there another new version of HTML? And what’s with the inconsistent spacing? As you’ll learn in Chapter 1, HTML5 has gone through two sets of hands. This process has left a few quirks behind, including a slightly schizophrenic versioning system. The read more..

  • Page - 18

    HTML5: THE MISSING MANUAL, SECOND EDITION XVI ABOUT THE OUTLINE Part Two: Video, Graphics, and Glitz • Chapter 5 hits one of HTML5’s most exciting features: its support for audio and video playback. You’ll learn how to survive Web Video Codec Wars to create playback pages that work in every browser, and you’ll even see how to create your own read more..

  • Page - 19

    INTRODUCTION XVII ABOUT THE ONLINE RESOURCES About the Online Resources As the owner of a Missing Manual, you’ve got more than just a book to read. Online, you’ll find example files as well as tips, articles, and maybe even a video or two. You can also communicate with the Missing Manual team and tell us what you love (or hate) about the read more..

  • Page - 20

    HTML5: THE MISSING MANUAL, SECOND EDITION XVIII SAFARI® BOOKS ONLINE Feedback Got questions? Need more information? Fancy yourself a book reviewer? On our Feedback page, you can get expert answers to questions that come to you while reading, share your thoughts on this Missing Manual, and find groups of folks who share your interest in creating their read more..

  • Page - 21

    Modern Markup PART 1 CHAPTER 1: Introducing HTML5 CHAPTER 2: Structuring Pages with Semantic Elements CHAPTER 3: Writing More Meaningful Markup CHAPTER 4: Building Better Web Forms read more..

  • Page - 22

    read more..

  • Page - 23

    3 CHAPTER 1 If HTML were a movie, HTML5 would be its surprise twist. HTML wasn’t meant to survive into the 21st century. The official web standards organization, the W3C (short for World Wide Web Consortium), left HTML for dead way back in 1998. The W3C pinned its future plans on a specification called XHTML, which it intended to read more..

  • Page - 24

    HTML5: THE MISSING MANUAL, SECOND EDITION 4 THE STORY OF HTML5 XHTML 1.0: Getting Strict XHTML has most of the same syntax conventions as HTML, but it enforces stricter rules. Much of the sloppy markup that traditional HTML permitted just isn’t accept- able in XHTML. For example, suppose you want to italicize the last word in a heading, like so: read more..

  • Page - 25

    CHAPTER 1: INTRODUCING HTML5 5 THE STORY OF HTML5 These changes were typical of XHTML 2. In theory, they made for cleaner, more logical markup. In practice, the changes forced web designers to alter the way they wrote web pages (to say nothing of updating the web pages they already had), and added no new features to make all that work read more..

  • Page - 26

    HTML5: THE MISSING MANUAL, SECOND EDITION 6 THE STORY OF HTML5 this point, the original HTML5 was broken into more manageable pieces, and many of the features that had originally been called HTML5 became separate standards (for more, see the box on this page).  TIP  You can read the official W3C version of the HTML5 standard at read more..

  • Page - 27

    CHAPTER 1: INTRODUCING HTML5 7 THREE KEY PRINCIPLES OF HTML5 When web developers hear about this plan, their first reaction is usually unmitigated horror. After all, who wants to deal with a world of wildly variable standards sup- port, where developers need to pick and choose the features they use based on the likelihood that these features read more..

  • Page - 28

    HTML5: THE MISSING MANUAL, SECOND EDITION 8 THREE KEY PRINCIPLES OF HTML5  NOTE  Unlike previous standards, HTML5 doesn’t just tell browser makers what to support—it also documents and formalizes the way they already work. Because the HTML5 standard documents reality, rather than just setting out a bunch of ideal rules, it may become the best-supported web standard read more..

  • Page - 29

    CHAPTER 1: INTRODUCING HTML5 9 THREE KEY PRINCIPLES OF HTML5  NOTE  Paving the cowpaths has an obvious benefit: It uses established techniques that already have some level of browser support. If you give web developers a choice between a beautifully designed new feature that works on 70 percent of the web browsers out there and a messy hack that works read more..

  • Page - 30

    HTML5: THE MISSING MANUAL, SECOND EDITION 10 YOUR FIRST LOOK AT HTML5 MARKUP Your First Look at HTML5 Markup Here’s one of the simplest HTML5 documents you can create: <!DOCTYPE html> <title>A Tiny HTML Document</title> <p>Let's rock the browser, HTML5 style.</p> It starts with the HTML5 doctype (a special code that’s explained on page 11), read more..

  • Page - 31

    CHAPTER 1: INTRODUCING HTML5 11 YOUR FIRST LOOK AT HTML5 MARKUP <!DOCTYPE html> <head> <title>A Tiny HTML Document</title> </head> <body> <p>Let's rock the browser, HTML5 style.</p> </body> As always, the indenting (at the beginning of lines three and six) is purely optional. This example uses it to make the structure of read more..

  • Page - 32

    HTML5: THE MISSING MANUAL, SECOND EDITION 12 YOUR FIRST LOOK AT HTML5 MARKUP The first thing you’ll notice about the HTML5 doctype is its striking simplicity. Compare it, for example, to the ungainly doctype that web developers need when using XHTML 1.0 strict: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" read more..

  • Page - 33

    CHAPTER 1: INTRODUCING HTML5 13 YOUR FIRST LOOK AT HTML5 MARKUP called UTF-8, which is compact, fast, and supports all the non-English characters you’ll ever need. Often, the web server that hosts your pages is configured to tell browsers that it’s serving out pages with a certain kind of encoding. However, because you can’t be sure that your read more..

  • Page - 34

    HTML5: THE MISSING MANUAL, SECOND EDITION 14 YOUR FIRST LOOK AT HTML5 MARKUP Adding a Style Sheet Virtually every web page in a properly designed, professional website uses CSS style sheets. You specify the style sheets you want to use by adding <link> elements to the <head> section of an HTML5 document, like this: <head> <meta read more..

  • Page - 35

    CHAPTER 1: INTRODUCING HTML5 15 YOUR FIRST LOOK AT HTML5 MARKUP <head> <meta charset="utf-8"> <!-- saved from url=(0014)about:internet --> <title>A Tiny HTML Document</title> <script src="scripts.js"></script> </head> This comment tells Internet Explorer to treat the page as though it has been down- loaded from a read more..

  • Page - 36

    HTML5: THE MISSING MANUAL, SECOND EDITION 16 A CLOSER LOOK AT HTML5 SYNTAX A Closer Look at HTML5 Syntax As you’ve already learned, HTML5 loosens some of the rules. That’s because the creators of HTML5 wanted the language to more closely reflect web browser real- ity—in other words, they wanted to narrow the gap between “web pages that read more..

  • Page - 37

    CHAPTER 1: INTRODUCING HTML5 17 A CLOSER LOOK AT HTML5 SYNTAX good style is the responsibility of the web designer, and the browser tolerates whatever you can throw at it. Here’s a quick summary of what constitutes good HTML5 style—and what conven- tions the examples in this book follow, even if they don’t have to: • Including the optional read more..

  • Page - 38

    HTML5: THE MISSING MANUAL, SECOND EDITION 18 A CLOSER LOOK AT HTML5 SYNTAX 1. In your web browser, go to http://validator.w3.org (Figure 1-2). The W3C validator gives you three choices, represented by three separate tabs: “Validate by URI” (for a page that’s already online), “Validate by File Upload” (for a page that’s stored in a read more..

  • Page - 39

    CHAPTER 1: INTRODUCING HTML5 19 A CLOSER LOOK AT HTML5 SYNTAX an HTML page that’s written in another language and the validator has trouble determining the correct character set. 3. Click the Check button. This click sends your HTML page to the W3C validator. After a brief delay, the report appears. You’ll see whether your document passed the read more..

  • Page - 40

    HTML5: THE MISSING MANUAL, SECOND EDITION 20 A CLOSER LOOK AT HTML5 SYNTAX But what if you want to enforce the XHTML syntax rules? Maybe you’re worried that you (or the people you work with) will inadvertently slip into the looser conven- tions of ordinary HTML. To stop that from happening, you need to use XHTML5—a less common standard that read more..

  • Page - 41

    CHAPTER 1: INTRODUCING HTML5 21 HTML5’S ELEMENT FAMILY specific XML-related goal in mind; for example, developers who want to manipulate the content in their pages with XML-related standards like XQuery and XPath.  TIP  If you’re curious, you can trick your browser into switching into XHTML mode. Just rename your file so that it ends with .xhtml or .xht. read more..

  • Page - 42

    HTML5: THE MISSING MANUAL, SECOND EDITION 22 HTML5’S ELEMENT FAMILY Removed Elements Although HTML5 adds new elements, it also boots a few out of the official family. These elements will keep working in browsers, but any decent HTML5 validator will smoke them out of their hiding places and complain loudly. Most obviously, HTML5 keeps the philosophy (first read more..

  • Page - 43

    CHAPTER 1: INTRODUCING HTML5 23 HTML5’S ELEMENT FAMILY  NOTE  Opinions on this <small> technique differ. On the one hand, it’s great for backward compatibility, because old browsers already support the <small> element, and so they’ll continue to support it in an HTML5 page. On the other hand, it introduces a potentially confusing change of meaning read more..

  • Page - 44

    HTML5: THE MISSING MANUAL, SECOND EDITION 24 HTML5’S ELEMENT FAMILY And here’s a snippet of markup that uses all four of these elements in the appropri- ate way: <strong>Breaking news!</strong> There's a sale on <i>leche quemada</i> candy at the <b>El Azul</b> restaurant. Don't delay, because when the last candy is gone, it's <em>gone</em>. In read more..

  • Page - 45

    CHAPTER 1: INTRODUCING HTML5 25 HTML5’S ELEMENT FAMILY There are also some tweaks that don’t work yet—in any browser. For example, the <ol> element (for ordered lists) now gets a reversed attribute, which you can set to count backward (either toward 1, or toward whatever starting value you set with the start attribute), but currently read more..

  • Page - 46

    HTML5: THE MISSING MANUAL, SECOND EDITION 26 USING HTML5 TODAY The <wbr> element has a natural similarity to the <nobr> element, which prevents text from wrapping no matter how narrow the available space. However, HTML5 considers <nobr> obsolete and advises all self-respecting web developers to avoid using it. Instead, you can get read more..

  • Page - 47

    CHAPTER 1: INTRODUCING HTML5 27 USING HTML5 TODAY  NOTE  Although really old versions of Internet Explorer—like IE 6 and IE 7—have finally disappeared from the scene, the problematic IE 8 and IE 9 still account for over 10 percent of all Web traffic (at the time of this writing). And because it’s never OK to force one in ten website visitors to read more..

  • Page - 48

    HTML5: THE MISSING MANUAL, SECOND EDITION 28 USING HTML5 TODAY 2. Choose the feature you want to study. The quickest way to find a feature is to type its name into the Search box near the top of the page. Or, you can browse to the feature by clicking one of the links on the front page. The HTML5 group has a set of links that are read more..

  • Page - 49

    CHAPTER 1: INTRODUCING HTML5 29 USING HTML5 TODAY FIGURE 1-4 This search for audio finds two tables. First is the table that describes browser support for the <audio> element (shown here). Green-shaded squares indicate browser versions that have full audio support, while red-shaded squares indicate browser versions that do not. read more..

  • Page - 50

    HTML5: THE MISSING MANUAL, SECOND EDITION 30 USING HTML5 TODAY How to Find Out Which Browsers Are on the Web How do you know which browser versions you need to worry about? Browser adop- tion statistics can tell you what portion of your audience has a browser that supports the features you plan to use. One good place to get read more..

  • Page - 51

    CHAPTER 1: INTRODUCING HTML5 31 USING HTML5 TODAY 4. Optionally, click the text next to the Period setting to pick a different date range. You’ll usually see the browser usage trends for an entire year, but you can choose to focus on a smaller range, like the past three months. 5. Optionally, change the chart type using the option buttons read more..

  • Page - 52

    HTML5: THE MISSING MANUAL, SECOND EDITION 32 USING HTML5 TODAY Here’s how to use Modernizr in one of your web pages: 1. Visit the Modernizr download page at http://modernizr.com/download. Look for the “Development version” link, which points to the latest all-in-one JavaScript file for Modernizr. 2. Right click the “Development version” link read more..

  • Page - 53

    CHAPTER 1: INTRODUCING HTML5 33 USING HTML5 TODAY <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>HTML5 Feature Detection</title> <script src="modernizr-latest.js"></script> </head> <body> <p>The verdict is... <span id="result"></span></p> <script> // Find the element read more..

  • Page - 54

    HTML5: THE MISSING MANUAL, SECOND EDITION 34 USING HTML5 TODAY The full Modernizr script is a bit bulky. It’s intended for testing purposes while you’re still working on your website. Once you’ve finished development and you’re ready to go live, you can create a slimmed-down version of the Modernizr script that tests only for the features you read more..

  • Page - 55

    CHAPTER 1: INTRODUCING HTML5 35 USING HTML5 TODAY Feature “Filling” with Polyfills Modernizr helps you spot the holes in browser support. It alerts you when a feature won’t work. However, it doesn’t do anything to patch these problems. That’s where polyfills come in. Basically, polyfills are a hodgepodge collection of techniques for filling read more..

  • Page - 56

    read more..

  • Page - 57

    37 CHAPTER 2 Over the two decades that the Web’s been around, websites have changed dramatically. But the greatest surprise isn’t how much the Web has changed, but how well ancient HTML elements have held up. In fact, web developers use the same set of elements to build today’s modern sites that they used to build their predecessors 10 read more..

  • Page - 58

    HTML5: THE MISSING MANUAL, SECOND EDITION 38 INTRODUCING THE SEMANTIC ELEMENTS  TIP  If your CSS skills are so rusty that you need a tetanus shot before you can crack open a style sheet, then you’re not quite ready for this chapter. Fortunately, Appendix A, “Essential CSS,” has a condensed introduction that covers the fundamentals. Introducing the Semantic read more..

  • Page - 59

    CHAPTER 2: STRUCTURING PAGES WITH SEMANTIC ELEMENTS 39 RETROFITTING A TRADITIONAL HTML PAGE • Accessibility. One of the key themes of modern web design is making acces- sible pages—that is, pages that people can navigate using screen readers and other assistive tools. Accessibility tools that understand HTML5 can provide a far better browsing experience read more..

  • Page - 60

    HTML5: THE MISSING MANUAL, SECOND EDITION 40 RETROFITTING A TRADITIONAL HTML PAGE FIGURE 2-1 This ordinary HTML page has a basic, document-like structure. A linked style sheet provides all the formatting. Page Structure the Old Way There are a number of ways to format a page like the one shown in Figure 2-1. Hap- pily, this example uses HTML best read more..

  • Page - 61

    CHAPTER 2: STRUCTURING PAGES WITH SEMANTIC ELEMENTS 41 RETROFITTING A TRADITIONAL HTML PAGE Here’s a shortened version of the markup, which highlights where the document plugs into its style sheet: <div class="Header"> <h1>How the World Could End</h1> <p class="Teaser">Scenarios that spell the end of life as we know read more..

  • Page - 62

    HTML5: THE MISSING MANUAL, SECOND EDITION 42 RETROFITTING A TRADITIONAL HTML PAGE FIGURE 2-2 The <div> elements carve this page into three logical sections: the header at the top, the content that follows, and the footer at the bottom. Here, the style sheet formatting tasks are simple. The entire page is given a maxi- mum width (800 pixels) to prevent read more..

  • Page - 63

    CHAPTER 2: STRUCTURING PAGES WITH SEMANTIC ELEMENTS 43 RETROFITTING A TRADITIONAL HTML PAGE margin: 10px; text-align: center; } /* Format any <h1> headings in the header <div> (that's the article title). */ .Header h1 { margin: 0px; color: white; font-size: xx-large; } /* Format the subtitle in the header <div>. */ .Header .Teaser { margin: read more..

  • Page - 64

    HTML5: THE MISSING MANUAL, SECOND EDITION 44 RETROFITTING A TRADITIONAL HTML PAGE <header class="Header"> <h1>How the World Could End</h1> <p class="Teaser">Scenarios that spell the end of life as we know it</p> <p class="Byline">by Ray N. Carnation</p> </header> <div class="Content"> <p><span read more..

  • Page - 65

    CHAPTER 2: STRUCTURING PAGES WITH SEMANTIC ELEMENTS 45 RETROFITTING A TRADITIONAL HTML PAGE Here’s the revised style sheet that applies its formatting to the <header> element: /* Format the <header> (as a blue, bordered box.) */ header { ... } /* Format any <h1> headings in the <header> (that's the article title). */ header h1 { ... } /* read more..

  • Page - 66

    HTML5: THE MISSING MANUAL, SECOND EDITION 46 RETROFITTING A TRADITIONAL HTML PAGE <div class="Content"> <p><span class="LeadIn">Right now</span>, you're probably ...</p> <p>...</p> <h2>Mayan Doomsday</h2> <p>Skeptics suggest ...</p> ... </div> </article> <footer> <p read more..

  • Page - 67

    CHAPTER 2: STRUCTURING PAGES WITH SEMANTIC ELEMENTS 47 RETROFITTING A TRADITIONAL HTML PAGE The following example shows some HTML markup that adds a figure to the apocalyp- tic article. It also includes the paragraph that immediately precedes the figure and the one that follows it, so you can see exactly where the figure is placed in the markup. read more..

  • Page - 68

    HTML5: THE MISSING MANUAL, SECOND EDITION 48 RETROFITTING A TRADITIONAL HTML PAGE FIGURE 2-4 Now a figure graces the article. In the markup, it’s defined just after the first paragraph, so it floats to the left of the following text. Notice that the width of the caption is limited, to create a nice, packed paragraph. Of course it’s still up read more..

  • Page - 69

    CHAPTER 2: STRUCTURING PAGES WITH SEMANTIC ELEMENTS 49 RETROFITTING A TRADITIONAL HTML PAGE <figure class="FloatFigure"> <img src="human_skull.jpg"> <figcaption>A human skull lies on the sand</figcaption> </figure> Just make sure you don't set the alternate text with an empty string, because that means your image is purely read more..

  • Page - 70

    HTML5: THE MISSING MANUAL, SECOND EDITION 50 RETROFITTING A TRADITIONAL HTML PAGE We don't know how the universe started, so we can't be sure it won't just end, maybe today. <img src="quotes_end.png" alt="End quote"> </aside> <h2>Unexplained Singularity</h2> This time, the style sheet rule floats the pull-quote to the right. Here are read more..

  • Page - 71

    CHAPTER 2: STRUCTURING PAGES WITH SEMANTIC ELEMENTS 51 BROWSER COMPATIBILITY FOR THE SEMANTIC ELEMENTS Browser Compatibility for the Semantic Elements So far, this exercise has been a lot of fun. But the best-structured page is useless if it won’t work on older browsers. Fortunately, HTML5’s semantic elements are broadly supported on all modern read more..

  • Page - 72

    HTML5: THE MISSING MANUAL, SECOND EDITION 52 BROWSER COMPATIBILITY FOR THE SEMANTIC ELEMENTS Using the HTML5 Shiv That technique described in the previous section is enough to solve compatibility issues in most browsers, but “most” doesn’t include Internet Explorer 8 and older. Old versions of IE introduce a second challenge: They refuse to apply read more..

  • Page - 73

    CHAPTER 2: STRUCTURING PAGES WITH SEMANTIC ELEMENTS 53 DESIGNING A SITE WITH THE SEMANTIC ELEMENTS the page in restricted mode. That means you’ll see the infamous IE security bar at the top of the page, warning you that Internet Explorer has disabled all your scripts, including the HTML5 shiv. To run it, you need to explicitly click the security bar read more..

  • Page - 74

    HTML5: THE MISSING MANUAL, SECOND EDITION 54 DESIGNING A SITE WITH THE SEMANTIC ELEMENTS FIGURE 2-6 Here, the single-page article you considered previously has been placed in a complete content-based website. A site header caps the page; the content is underneath; and a sidebar on the left provides navigation controls, “About Us” information, and an image ad. read more..

  • Page - 75

    CHAPTER 2: STRUCTURING PAGES WITH SEMANTIC ELEMENTS 55 DESIGNING A SITE WITH THE SEMANTIC ELEMENTS UP TO SPEED Turning a Web Page into a Website Figure 2-6 shows a single page from a fictional website. In a real website, you’d have the same layout (and the same side panel) on dozens of different pages or more. The only thing that would read more..

  • Page - 76

    HTML5: THE MISSING MANUAL, SECOND EDITION 56 DESIGNING A SITE WITH THE SEMANTIC ELEMENTS FREQUENTLY ASKED QUESTION The Heading Structure of a Site Is it acceptable to have more than one level-1 heading on a page? Is it a good idea? According to the official rules of HTML, you can have as many level-1 headings as you want. However, read more..

  • Page - 77

    CHAPTER 2: STRUCTURING PAGES WITH SEMANTIC ELEMENTS 57 DESIGNING A SITE WITH THE SEMANTIC ELEMENTS example, if you have a list of articles (as in Figure 2-6), you definitely need a <nav> section. But if you have just a couple of links at the bottom of the page with licens- ing and contact information, a full-blown <nav> isn’t necessary. read more..

  • Page - 78

    HTML5: THE MISSING MANUAL, SECOND EDITION 58 DESIGNING A SITE WITH THE SEMANTIC ELEMENTS <div> <img src="ad.jpg" alt="Luckies cigarette ad: it's toasted"> </div> </aside> Here are the key points: • The title sections (“Articles” an d “About Us”) are level-2 headings. That way, they are clearly subordinate to the read more..

  • Page - 79

    CHAPTER 2: STRUCTURING PAGES WITH SEMANTIC ELEMENTS 59 DESIGNING A SITE WITH THE SEMANTIC ELEMENTS min-height: 1500px; background-color:#eee; font-size: small; } This rule is followed by contextual style sheet rules that format the <h2>, <ul> , <li>, and <img> elements in the sidebar. (As always, you can get the sample code from read more..

  • Page - 80

    HTML5: THE MISSING MANUAL, SECOND EDITION 60 DESIGNING A SITE WITH THE SEMANTIC ELEMENTS • Groups of content—for example, a collection of articles on a news site. • A portion of a longer document. For example, in the apocalyptic article, you could mark up each separate end-of-the-world scenario as a distinct section. Sometimes you’ll use read more..

  • Page - 81

    CHAPTER 2: STRUCTURING PAGES WITH SEMANTIC ELEMENTS 61 DESIGNING A SITE WITH THE SEMANTIC ELEMENTS Deeper into Footers HTML5 and fat headers were meant for each other. Not only can you stuff in subtitles and bylines, but you can also add images, navigational sections (with the <nav> ele- ment), and virtually anything else that belongs at the top of read more..

  • Page - 82

    HTML5: THE MISSING MANUAL, SECOND EDITION 62 DESIGNING A SITE WITH THE SEMANTIC ELEMENTS • A partially transparent background , so you can see the page content through the footer. This setup works well if the footer is advertising breaking news or an important disclaimer, and it’s usually used in conjunction with a close button. • Animation , so read more..

  • Page - 83

    CHAPTER 2: STRUCTURING PAGES WITH SEMANTIC ELEMENTS 63 DESIGNING A SITE WITH THE SEMANTIC ELEMENTS You could also choose to put the footer in an <aside> element, to clearly indicate that the footer content is a separate section, and tangentially related to the rest of the content on the page. Here’s what that structure looks like: <div read more..

  • Page - 84

    HTML5: THE MISSING MANUAL, SECOND EDITION 64 DESIGNING A SITE WITH THE SEMANTIC ELEMENTS <aside> ... </aside> <main> <article> ... </article> </main> <footer> ... </footer> </body> </html> You can’t put the <main> element inside the read more..

  • Page - 85

    CHAPTER 2: STRUCTURING PAGES WITH SEMANTIC ELEMENTS 65 THE HTML5 OUTLINING SYSTEM Here, the distinction is clear—each <article> represents a self-contained piece of content, but the main content of the page is the full set of articles. It’s appropriate to use the <main> element on any type of page, even if that page doesn’t include an read more..

  • Page - 86

    HTML5: THE MISSING MANUAL, SECOND EDITION 66 THE HTML5 OUTLINING SYSTEM work with files that are stored on your computer). An outline icon appears in the address bar, which reveals the structure of the page when clicked (Figure 2-10). The h5o page also provides a bookmarklet (a piece of JavaScript code that you can add to your web read more..

  • Page - 87

    CHAPTER 2: STRUCTURING PAGES WITH SEMANTIC ELEMENTS 67 THE HTML5 OUTLINING SYSTEM <h2>Robot Takeover</h2> ... <h2>Unexplained Singularity</h2> ... <h2>Runaway Climate Change</h2> ... <h2>Global Epidemic</h2> ... <div class="Footer"> ... </div> </body> This simple structure leads to an read more..

  • Page - 88

    HTML5: THE MISSING MANUAL, SECOND EDITION 68 THE HTML5 OUTLINING SYSTEM Finally, the outline algorithm is smart enough to ignore skipped levels. For example, if you write this slightly wobbly markup, which skips from <h1> directly to <h3>: <h1>Level-1 Heading</h1> <h2>Level-2 Heading</h2> <h1>Level-1 Heading</h1> <h3>Level-3 Heading</h3> read more..

  • Page - 89

    CHAPTER 2: STRUCTURING PAGES WITH SEMANTIC ELEMENTS 69 THE HTML5 OUTLINING SYSTEM <h2>Robot Takeover</h2> ... <h2>Unexplained Singularity</h2> ... <h2>Runaway Climate Change</h2> ... <h2>Global Epidemic</h2> ... </div> </article> read more..

  • Page - 90

    HTML5: THE MISSING MANUAL, SECOND EDITION 70 THE HTML5 OUTLINING SYSTEM 1. Apocalypse Today 1. Untitled Section 1. Articles 2. About Us 2. How the World Could End 1. Mayan Doomsday 2. Robot Takeover 3. Untitled Section 4. Unexplained read more..

  • Page - 91

    CHAPTER 2: STRUCTURING PAGES WITH SEMANTIC ELEMENTS 71 THE HTML5 OUTLINING SYSTEM ... <h3>Galapagos Islands</h3> ... <h3>The Swiss Alps</h3> ... </article> </body> GEM IN THE ROUGH How Sectioning Elements Help Complex Pages Sectioning is a great help with syndication and aggregation— two examples of the read more..

  • Page - 92

    HTML5: THE MISSING MANUAL, SECOND EDITION 72 THE HTML5 OUTLINING SYSTEM But the outline you actually get is this: 1. Untitled Section for the <body> 1. Natural Wonders to Visit Before You Die 1. In North America 1. The Grand Canyon 2. Yellowstone National Park 2. In the Rest of the World read more..

  • Page - 93

    CHAPTER 2: STRUCTURING PAGES WITH SEMANTIC ELEMENTS 73 THE HTML5 OUTLINING SYSTEM <section> <h2>In the Rest of the World</h2> ... </section> <aside>...</aside> ... <section> <h3>Galapagos Islands</h3> ... </section> read more..

  • Page - 94

    HTML5: THE MISSING MANUAL, SECOND EDITION 74 THE HTML5 OUTLINING SYSTEM <h3>Galapagos Islands</h3> ... <h3>The Swiss Alps</h3> ... </section> </article> </body> Now, the outline algorithm doesn’t need to create an automatic section for the sec- ond <h2>, and so there’s read more..

  • Page - 95

    75 CHAPTER 3 In the previous chapter, you met HTML5’s semantic elements. With their help, you can give your pages a clean, logical structure and prepare for a future of super- smart browsers, search engines, and assistive devices. But you haven’t reached the end of the semantic story yet. Semantics are all about adding meaning to your markup, read more..

  • Page - 96

    HTML5: THE MISSING MANUAL, SECOND EDITION 76 THE SEMANTIC ELEMENTS REVISITED The Semantic Elements Revisited There’s a reason you began your exploration into semantics with the page structure elements (see Table 3-1 for a recap). Quite simply, page structure is an easy chal- lenge. That’s because the vast majority of websites use a small set of read more..

  • Page - 97

    CHAPTER 3: WRITING MORE MEANINGFUL MARKUP 77 THE SEMANTIC ELEMENTS REVISITED Text-level semantics are a tougher nut to crack. That’s because people use a huge number of different types of content. If HTML5 set out to create an element for every sort of information you might add to a page, the language would be swim- ming in a mess of read more..

  • Page - 98

    HTML5: THE MISSING MANUAL, SECOND EDITION 78 THE SEMANTIC ELEMENTS REVISITED The <time> element has similar rules about times, which you supply in this format: HH:MM That’s a two-digit hour (using a 24-hour clock), followed by a two-digit number of minutes, like this: Parties start every night at <time datetime="16:30">4:30 p.m.</time>. read more..

  • Page - 99

    CHAPTER 3: WRITING MORE MEANINGFUL MARKUP 79 THE SEMANTIC ELEMENTS REVISITED For example, imagine you create a page like the one shown in Figure 3-1. This figure lets the user enter some information. A script then takes this information, performs a calculation, and displays the result just underneath. FIGURE 3-1 It’s a time-honored web design pattern. read more..

  • Page - 100

    HTML5: THE MISSING MANUAL, SECOND EDITION 80 THE SEMANTIC ELEMENTS REVISITED Often, this sort of page has its controls inside a <form> element. In this example, that’s the three text boxes where people can type in information: <form action="#" id="bmiCalculator"> <label for="feet inches">Height:</label> <input read more..

  • Page - 101

    CHAPTER 3: WRITING MORE MEANINGFUL MARKUP 81 THE SEMANTIC ELEMENTS REVISITED The text in a <mark> element gets the yellow background shown in Figure 3-2. FIGURE 3-2 Here, the <mark> ele- ment highlights important details in a block of quoted text. You can also use <mark> to flag important content or keywords, as search engines do when read more..

  • Page - 102

    HTML5: THE MISSING MANUAL, SECOND EDITION 82 OTHER STANDARDS THAT BOOST SEMANTICS mark { background-color: yellow; color: black; } You’ll also need the Internet Explorer workaround described on page 51 to make the <mark> element style-able in old versions of IE. Other Standards That Boost Semantics At this point, it’s probably read more..

  • Page - 103

    CHAPTER 3: WRITING MORE MEANINGFUL MARKUP 83 OTHER STANDARDS THAT BOOST SEMANTICS Of course, you learned last chapter that HTML5 also gives you a more meaningful way to mark up headers. So what you really should use is something like this: <header role="banner"> This example demonstrates two important facts. First, ARIA requires you to read more..

  • Page - 104

    HTML5: THE MISSING MANUAL, SECOND EDITION 84 OTHER STANDARDS THAT BOOST SEMANTICS Microformats Microformats are a simple, streamlined approach to putting metadata in your pages. Microformats don’t attempt to be any sort of official standard. Instead, they’re a loose collection of agreed-upon conventions that let pages share structured information read more..

  • Page - 105

    CHAPTER 3: WRITING MORE MEANINGFUL MARKUP 85 OTHER STANDARDS THAT BOOST SEMANTICS Once you’ve worked your way around hCard, you’ll have no trouble understanding hCalendar, the world’s second-most-popular microformat. Using hCalendar, you can mark up appointments, meetings, holidays, product releases, store openings, and so on. Just wrap read more..

  • Page - 106

    HTML5: THE MISSING MANUAL, SECOND EDITION 86 OTHER STANDARDS THAT BOOST SEMANTICS attention to this information, but their traffic-driving, web-shaping clout is undeni- able. (You’ll see how search engines use this sort of information starting on page 94.)  NOTE  It now seems possible that microdata just might catch on as the Goldilocks standard for read more..

  • Page - 107

    CHAPTER 3: WRITING MORE MEANINGFUL MARKUP 87 OTHER STANDARDS THAT BOOST SEMANTICS Here’s a microdata-fied version of the hCard microformat you saw earlier: <div itemscope itemtype="http://schema.org/Person"> <h3 itemprop="name">Mike Rowe</h3> You can see Mike Rowe’s website at <a itemprop="url" read more..

  • Page - 108

    HTML5: THE MISSING MANUAL, SECOND EDITION 88 A PRACTICAL EXAMPLE: RETROFITTING AN “ABOUT ME” PAGE  NOTE  The three standards for rich semantic data—RDFa, microdata, and microformats—all share broad similarities. They aren’t quite compatible, but the markup is similar enough that the skills you pick up learning one system are mostly applicable to the others. A read more..

  • Page - 109

    CHAPTER 3: WRITING MORE MEANINGFUL MARKUP 89 A PRACTICAL EXAMPLE: RETROFITTING AN “ABOUT ME” PAGE <a href="http://www.magicsemantics.com">www.magicsemantics.com</a> </p> FIGURE 3-4 This “About Me” page includes the website author’s contact details, before adding any microdata. Clearly, this is a good fit for the familiar Person vocabulary (detailed read more..

  • Page - 110

    HTML5: THE MISSING MANUAL, SECOND EDITION 90 A PRACTICAL EXAMPLE: RETROFITTING AN “ABOUT ME” PAGE <p>You can contact him where he works, at The Magic Semantic Company</span> (phone <span itemprop="telephone">641-545-0234</span> and ask for Mike) or email <span itemprop="email">mike-f@magicsemantics.com</span>.</p> <p>Or, read more..

  • Page - 111

    CHAPTER 3: WRITING MORE MEANINGFUL MARKUP 91 A PRACTICAL EXAMPLE: RETROFITTING AN “ABOUT ME” PAGE <p>Or, visit Mike on the job at:<br> <span itemprop="address" itemscope itemtype="http://schema.org/PostalAddress"> ... </span> </div> You can then fill in the address details inside the new section: <div read more..

  • Page - 112

    HTML5: THE MISSING MANUAL, SECOND EDITION 92 A PRACTICAL EXAMPLE: RETROFITTING AN “ABOUT ME” PAGE FIGURE 3-5 The Person vocabulary accepts a long list of properties (only some of which are shown here). Most properties take ordinary text, numbers, or date values. But some (like the address property, shown here) use their own vocabularies (like read more..

  • Page - 113

    CHAPTER 3: WRITING MORE MEANINGFUL MARKUP 93 HOW SEARCH ENGINES USE METADATA FIGURE 3-6 The Semantic Inspector is a Chrome extension that extracts all the microdata on the current page. Click its toolbar button, and you’ll get the semantic skinny. Here, the Semantic Inspector examines the “About Me” page. The best bet for a microdata future may be for read more..

  • Page - 114

    HTML5: THE MISSING MANUAL, SECOND EDITION 94 HOW SEARCH ENGINES USE METADATA visitor to click through to your site. Good metadata can help with the last part of this equation. All you do is put the right semantic data on your page, and a search engine like Google will use it to present a fancier search listing, which can help your read more..

  • Page - 115

    CHAPTER 3: WRITING MORE MEANINGFUL MARKUP 95 HOW SEARCH ENGINES USE METADATA FIGURE 3-7 Here, Google found the person contact details and address information (from the microdata example shown on page 89). It used this information to add a gray byline under the page title with some of the personal details. 2. If you want to paste in your markup, read more..

  • Page - 116

    HTML5: THE MISSING MANUAL, SECOND EDITION 96 HOW SEARCH ENGINES USE METADATA 3. Type in your URL or paste in your markup. Then click Preview. You can now review the results (see Figure 3-7). There are two important sec- tions to review. The “Google search preview” section shows how the page may appear in a search result. The “Extracted rich read more..

  • Page - 117

    CHAPTER 3: WRITING MORE MEANINGFUL MARKUP 97 HOW SEARCH ENGINES USE METADATA <div itemprop="itemReviewed" itemscope itemtype="http://schema.org/Thing"> <span itemprop="name">Jan's Pizza House</span> </div> <div> <span itemprop="author" itemscope itemtype="http://schema.org/Person"> Reviewed by: <span read more..

  • Page - 118

    HTML5: THE MISSING MANUAL, SECOND EDITION 98 HOW SEARCH ENGINES USE METADATA Keen eyes will notice that there are actually four microdata formats at work in this single review. There’s one format for the review itself ( http://schema.org/Review), one for the thing you’re reviewing ( http://schema.org/Thing), one for the person do- ing the reviewing ( read more..

  • Page - 119

    CHAPTER 3: WRITING MORE MEANINGFUL MARKUP 99 HOW SEARCH ENGINES USE METADATA TROUBLESHOOTING MOMENT What to Do When Google Ignores Your Semantic Data Just because Google can show a semantically enriched page in a certain special way doesn’t mean it will. Google uses its own set of semi-secret rules to determine whether the semantic read more..

  • Page - 120

    HTML5: THE MISSING MANUAL, SECOND EDITION 100 HOW SEARCH ENGINES USE METADATA <div itemprop="nutrition" itemscope itemtype="http://data-vocabulary.org/Nutrition"> Serving size: <span itemprop="servingSize">1 large bowl</span> Calories per serving: <span itemprop="calories">250</span> Fat per serving: <span read more..

  • Page - 121

    CHAPTER 3: WRITING MORE MEANINGFUL MARKUP 101 HOW SEARCH ENGINES USE METADATA  NOTE  Recipes tend to be long and fairly detailed, so marking them up is a long and involved project. This is a clear case where a good authoring tool could make a dramatic difference. Ideally, this tool would let web authors enter the recipe details in the text boxes of a read more..

  • Page - 122

    HTML5: THE MISSING MANUAL, SECOND EDITION 102 HOW SEARCH ENGINES USE METADATA FIGURE 3-10 After you perform a recipe search, Google lets you filter the results based on some of the metadata that it found in the matching recipes. Here, a search hunts for a tomato soup recipe that’s heavy on the basil but avoids tomato juice. The semantic data read more..

  • Page - 123

    103 CHAPTER 4 HTML forms are simple HTML controls you use to collect information from website visitors. They include text boxes people can type into, list boxes they can pick from, checkboxes they can switch on or off, and so on. On the Web, forms let people do everything from getting stock quotes to buying concert tickets. HTML read more..

  • Page - 124

    HTML5: THE MISSING MANUAL, SECOND EDITION 104 UNDERSTANDING FORMS over the differences. You’ll also consider a feature that isn’t technically part of the HTML5 forms standard but is all about interactivity—putting a rich HTML editor in an ordinary web page. Understanding Forms Odds are that you’ve worked with forms before. But if you’re a bit sketchy on read more..

  • Page - 125

    CHAPTER 4: BUILDING BETTER WEB FORMS 105 REVAMPING A TRADITIONAL HTML FORM The tricky part of this discussion is that there are hundreds of ways to build the server-side part of the equation—that’s th e application that processes the information that’s submitted from the form. Some developers may use stripped-down scripts that let them manipulate the read more..

  • Page - 126

    HTML5: THE MISSING MANUAL, SECOND EDITION 106 REVAMPING A TRADITIONAL HTML FORM FIGURE 4-2 If you’ve traveled the Web, you’ve seen your share of forms like this one, which collects basic information from a web page visitor. The <form> element bundles together all the form widgets (also known as controls or fields). It also tells the browser where to read more..

  • Page - 127

    CHAPTER 4: BUILDING BETTER WEB FORMS 107 REVAMPING A TRADITIONAL HTML FORM  NOTE  HTML5 adds a mechanism for placing form controls outside of the form to which they belong. The trick is to use the new form attribute to refer to the form by its id value (as in form="zooForm"). However, browsers that don’t support this feature will completely read more..

  • Page - 128

    HTML5: THE MISSING MANUAL, SECOND EDITION 108 REVAMPING A TRADITIONAL HTML FORM TABLE 4-1 Form controls CONTROL HTML ELEMENT DESCRIPTION Single-line textbox <input type="text"> <input type="password"> Shows a text box where visitors can type in text. If you use the password type, the browser won’t display the text. Instead, visitors see an asterisk (*) or a read more..

  • Page - 129

    CHAPTER 4: BUILDING BETTER WEB FORMS 109 REVAMPING A TRADITIONAL HTML FORM <label for="comments">When did you first know you wanted to be a zoo-keeper?</label> <textarea id="comments"></textarea> </fieldset> <fieldset> <legend>Pick Your Favorite Animals</legend> <label read more..

  • Page - 130

    HTML5: THE MISSING MANUAL, SECOND EDITION 110 REVAMPING A TRADITIONAL HTML FORM To create a placeholder, simply use the placeholder attribute: <label for="name">Name <em>*</em></label> <input id="name" placeholder="Jane Smith "><br> <label for="telephone">Telephone</label> <input id="telephone" placeholder="(xxx) read more..

  • Page - 131

    CHAPTER 4: BUILDING BETTER WEB FORMS 111 REVAMPING A TRADITIONAL HTML FORM UP TO SPEED Writing Good Placeholders You don’t need placeholders for every text box. Instead, you should use them to clear up potential ambiguity. For example, no one needs an explanation about what goes in a First Name box, but the Name box in Figure 4-4 isn’t read more..

  • Page - 132

    HTML5: THE MISSING MANUAL, SECOND EDITION 112 VALIDATION: STOPPING ERRORS The autofocus attribute has similar support as the placeholder attribute, which means basically every browser recognizes it except IE 9 and older. Once again, it’s easy enough to plug the hole. You can check for autofocus support using Modernizr (page 31) and then run your own read more..

  • Page - 133

    CHAPTER 4: BUILDING BETTER WEB FORMS 113 VALIDATION: STOPPING ERRORS UP TO SPEED Validating in Two Places Throughout the years, crafty developers have approached the validation problem in different ways. Today, the consensus is clear. To make a bulletproof form, you need two types of error-checking: • Client-side validation. These are the checks read more..

  • Page - 134

    HTML5: THE MISSING MANUAL, SECOND EDITION 114 VALIDATION: STOPPING ERRORS FIGURE 4-5 Here’s the same required field in Chrome (top), Inter- net Explorer (middle), and Firefox (bottom). Browsers are free to choose the exact way they notify people about validation problems, but they all use a pop-up box that looks like a styl- ized tooltip. Unfortunately, you read more..

  • Page - 135

    CHAPTER 4: BUILDING BETTER WEB FORMS 115 VALIDATION: STOPPING ERRORS The other option is to provide a submit button that bypasses validation. This tech- nique is sometimes useful in a web page. For example, you may want to enforce strict validation for the official submit button but provide another button that does something else (like storing half-completed read more..

  • Page - 136

    HTML5: THE MISSING MANUAL, SECOND EDITION 116 VALIDATION: STOPPING ERRORS You can use all sorts of other tricks, like combining the validation pseudo-classes with the focus pseudo-class, or using an offset background that includes an error icon to flag invalid values. Of course, a hefty disclaimer applies: You can use these pseudo-classes to improve read more..

  • Page - 137

    CHAPTER 4: BUILDING BETTER WEB FORMS 117 VALIDATION: STOPPING ERRORS Regular expressions quickly get much more complex than this example. Writing a regular expression can be quite a chore, which is why most developers simply search for a ready-made regular expression that validates the type of data they want to check. Or they get help.  TIP  To read more..

  • Page - 138

    HTML5: THE MISSING MANUAL, SECOND EDITION 118 VALIDATION: STOPPING ERRORS Here’s how it works. First, you need to check the appropriate field for errors. You do this by handling the onInput event, which is nothing new: <label for="comments">When did you first know you wanted to be a zookeeper?</label> <textarea id="comments" read more..

  • Page - 139

    CHAPTER 4: BUILDING BETTER WEB FORMS 119 BROWSER SUPPORT FOR WEB FORMS AND VALIDATION Of course, you could solve this problem more neatly with a regular expression that requires long strings. But while regular expressions are great for validating some data types, custom validation logic can do anything, from complex algebra to con- tacting the web server. read more..

  • Page - 140

    HTML5: THE MISSING MANUAL, SECOND EDITION 120 BROWSER SUPPORT FOR WEB FORMS AND VALIDATION Testing for Support with Modernizr If all your form needs is a smattering of simple validation, it’s probably worth adding your own checks. Using Modernizr (page 31), you can check for a variety of HTML5 web forms features. For example, use the Modernizr.input.pattern read more..

  • Page - 141

    CHAPTER 4: BUILDING BETTER WEB FORMS 121 BROWSER SUPPORT FOR WEB FORMS AND VALIDATION // If you reach this point, everything worked out and the browser // can submit the form. return true; } }  TIP  This block of code relies on a number of basic JavaScript techniques, including element lookup, a loop, and conditional logic. To learn read more..

  • Page - 142

    HTML5: THE MISSING MANUAL, SECOND EDITION 122 BROWSER SUPPORT FOR WEB FORMS AND VALIDATION The second reference is to the HTML5Forms library. After the familiar src attribute, you’ll see one or more attributes that specify the features you need. In the example above, the script loads all the webforms features. HTML5Forms is a modular library, read more..

  • Page - 143

    CHAPTER 4: BUILDING BETTER WEB FORMS 123 NEW TYPES OF INPUT New Types of Input One of the quirks of HTML forms is that one ingredient—the vaguely named <input> element—is used to create a variety of controls, from checkboxes to text boxes to buttons. The type attribute is the master switch that determines what each <input> element read more..

  • Page - 144

    HTML5: THE MISSING MANUAL, SECOND EDITION 124 NEW TYPES OF INPUT FIGURE 4-8 When people use a mobile device to fill out a form, they don’t have the luxury of entering information on a full keyboard. The iPod makes life easier by customizing the virtual keyboard depending on the data type, so telephone numbers get a telephone-style numeric keypad (left), read more..

  • Page - 145

    CHAPTER 4: BUILDING BETTER WEB FORMS 125 NEW TYPES OF INPUT DATA TYPE IE FIREFOX CHROME SAFARI OPERA number 10 - 10 5 9 range 10 23 6 5 11 date, month, week, time --10 - 11 color --20 - -** * The HTML5 standard does not require validation for this data type. ** Opera supported the color input type in versions 11 and 12, but removed this support in more read more..

  • Page - 146

    HTML5: THE MISSING MANUAL, SECOND EDITION 126 NEW TYPES OF INPUT URLs URLs use the url type. What constitutes a valid URL is still a matter of hot debate. But most browsers use a relatively lax validation algorithm. It requires a URL prefix (which could be legitimate, like http://, or made up, like bonk://), and accepts spaces and most read more..

  • Page - 147

    CHAPTER 4: BUILDING BETTER WEB FORMS 127 NEW TYPES OF INPUT Of course, there are plenty of numbers, and they aren’t all appropriate for every kind of data. The markup shown above allows ages like 43,000 and -6. To fix this, you need to use the min and max attributes. Here’s an example that limits ages to the reasonable range of 0 read more..

  • Page - 148

    HTML5: THE MISSING MANUAL, SECOND EDITION 128 NEW TYPES OF INPUT FIGURE 4-11 You’ve probably used range-like controls to set things like sound volume. They work well for information where there’s a narrow range of values between a known mini- mum and a known maximum, and the specific numeric value isn’t important (but the placement of that value relative to the read more..

  • Page - 149

    CHAPTER 4: BUILDING BETTER WEB FORMS 129 NEW TYPES OF INPUT  TIP  If you decide to use one of the date types, consider using a polyfill like HTML5Forms library (page 121) for older browsers. That’s because it’s easy for people on non-supporting browsers to enter dates in the wrong format, and it’s tedious for you to validate date data and provide the read more..

  • Page - 150

    HTML5: THE MISSING MANUAL, SECOND EDITION 130 NEW ELEMENTS In browsers that don’t support the color type, form-fillers will need to type a hexa- decimal color code on their own (or you can use the Html5Forms library described on page 121). New Elements So far, you’ve learned how HTML5 extends forms with new validation features and how it gets read more..

  • Page - 151

    CHAPTER 4: BUILDING BETTER WEB FORMS 131 NEW ELEMENTS To use a datalist, you must first start with a standard text box. For example, imagine you have an ordinary <input> element like this: <legend>What's Your Favorite Animal?</legend> <input id="favoriteAnimal"> To add a drop-down list of suggestions, you need to create a datalist. read more..

  • Page - 152

    HTML5: THE MISSING MANUAL, SECOND EDITION 132 NEW ELEMENTS <select id="favoriteAnimalPreset"> <option label="Alpaca" value="alpaca"> <option label="Zebra" value="zebra"> <option label="Cat" value="cat"> <option label="Caribou" value="caribou"> <option label="Caterpillar" read more..

  • Page - 153

    CHAPTER 4: BUILDING BETTER WEB FORMS 133 NEW ELEMENTS This effect isn’t completely seamless. When you receive the form data on the web server, you need to check for data from the list (in this example, that’s favoriteAnimalPreset) and from the text box (that’s favoriteAnimal). But other than this minor wrinkle, you’ve got a solid way to read more..

  • Page - 154

    HTML5: THE MISSING MANUAL, SECOND EDITION 134 NEW ELEMENTS  NOTE  Technically, the new <meter> and <progress> elements don’t need to be in a form. In fact, they aren’t even real controls (because they don’t collect input from the web page visitor). However, the official HTML5 standard lumps them all together, because in some respects the <progress> read more..

  • Page - 155

    CHAPTER 4: BUILDING BETTER WEB FORMS 135 NEW ELEMENTS The <meter> element has a similar model, but it indicates any sort of measurement. The <meter> element is sometimes described as a gauge. Often, the specific meter value you use will correspond to something in the real world (for example, an amount of money, a number of days, an read more..

  • Page - 156

    HTML5: THE MISSING MANUAL, SECOND EDITION 136 AN HTML EDITOR IN A WEB PAGE An HTML Editor in a Web Page As you learned in Chapter 1, HTML5 believes in paving cowpaths—in other words, taking the unstandardized features that developers use today and making them part of the official HTML5 standard. One of the single best examples is its inclusion of read more..

  • Page - 157

    CHAPTER 4: BUILDING BETTER WEB FORMS 137 AN HTML EDITOR IN A WEB PAGE FIGURE 4-16 When you click in an edit- able region, you can move around using the arrow keys, delete text, and insert new content (left). You can also select text with the Shift key and then copy, cut, and paste it (right). It’s a bit like typing in a word processor, only you won’t read more..

  • Page - 158

    HTML5: THE MISSING MANUAL, SECOND EDITION 138 AN HTML EDITOR IN A WEB PAGE And here are two buttons that use them: <button onclick="startEdit()">Start Editing</button> <button onclick="stopEdit()">Stop Editing</button> Just make sure you don’t place the buttons in the editable region of your page, because when a page is being edited, its read more..

  • Page - 159

    CHAPTER 4: BUILDING BETTER WEB FORMS 139 AN HTML EDITOR IN A WEB PAGE FIGURE 4-18 This page contains two boxes. The first is an <iframe> that shows the apocalypse page example from Chapter 2. The second is an ordinary <div> that shows the HTML markup of the page after it’s been edited. The two buttons at the top of the page control the read more..

  • Page - 160

    HTML5: THE MISSING MANUAL, SECOND EDITION 140 AN HTML EDITOR IN A WEB PAGE As you can see, this example relies on the startEdit() and stopEdit() methods, much like the previous example. However, the code is tweaked so that it sets the designMode attribute rather than the contenteditable attribute: function startEdit() { // Turn on design mode read more..

  • Page - 161

    Video, Graphics, and Glitz PART 2 CHAPTER 5: Audio and Video CHAPTER 6: Fancy Fonts and Effects with CSS3 CHAPTER 7: Responsive Web Design with CSS3 CHAPTER 8: Basic Drawing with the Canvas CHAPTER 9: Advanced Canvas: Interactivity and Animation read more..

  • Page - 162

    read more..

  • Page - 163

    143 CHAPTER 5 There was a time when the Internet was primarily a way to share academic research. Then things changed and the Web grew into a news and commerce powerhouse. Today the Internet’s state-of-the-art networking technology is used less for physics calculations and more for spreading viral videos of piano-playing kittens across the planet. And read more..

  • Page - 164

    HTML5: THE MISSING MANUAL, SECOND EDITION 144 THE EVOLUTION OF WEB VIDEO The Evolution of Web Video Without HTML5, you have a couple of ways to add video to a web page. One old- fashioned approach is to shoehorn it into a page with the <embed> element. The browser then creates a video window that uses Windows Media Player, Apple QuickTime, read more..

  • Page - 165

    CHAPTER 5: AUDIO AND VIDEO 145 INTRODUCING HTML5 AUDIO AND VIDEO Introducing HTML5 Audio and Video A simple idea underpins HTML5’s audio and video support. Just as you can add images to a web page with the <img> element, you should be able to insert sound with an <audio> element and video with a <video> element. Logically read more..

  • Page - 166

    HTML5: THE MISSING MANUAL, SECOND EDITION 146 INTRODUCING HTML5 AUDIO AND VIDEO  NOTE  The <audio> and <video> elements must have both a start and an end tag. You can’t use empty element syntax, like <audio />. FIGURE 5-1 Here’s what playback controls look like on three browsers: Internet Explorer (top), Google Chrome (middle), and Firefox (bottom). read more..

  • Page - 167

    CHAPTER 5: AUDIO AND VIDEO 147 INTRODUCING HTML5 AUDIO AND VIDEO If you don’t set the preload attribute, browsers can do what they want, and different browsers make different assumptions. Most browsers assume auto as the default value, but Firefox uses metadata. Furthermore, it’s important to note that the preload attribute isn’t a rigid read more..

  • Page - 168

    HTML5: THE MISSING MANUAL, SECOND EDITION 148 INTRODUCING HTML5 AUDIO AND VIDEO Once again, the controls attribute gets the browser to generate a set of handy playback controls (Figure 5-2). In most browsers, these controls disappear when you click somewhere else on the page and return when you hover over the movie. FIGURE 5-2 The <video> element read more..

  • Page - 169

    CHAPTER 5: AUDIO AND VIDEO 149 UNDERSTANDING THE HTML5 MEDIA FORMATS Finally, the poster attribute lets you supply an image that should be used in place of the video. Browsers use this picture in three situations: if the first frame of the video hasn’t been downloaded yet, if you’ve set the preload attribute to none, or if the selected read more..

  • Page - 170

    HTML5: THE MISSING MANUAL, SECOND EDITION 150 UNDERSTANDING THE HTML5 MEDIA FORMATS FIGURE 5-3 If you load a page that uses an H.264 video in Opera, the playback controls are disabled, and a blank space appears where the video should be. Fortunately, you can solve this problem with a format fallback, as you’ll see on page 155. But before you learn how to read more..

  • Page - 171

    CHAPTER 5: AUDIO AND VIDEO 151 UNDERSTANDING THE HTML5 MEDIA FORMATS FORMAT DESCRIPTION COMMON FILE EXTENSION MIME TYPE H.264 The industry standard for video encoding, particularly when dealing with high- definition video. Used by consumer devices (like Blu-ray players and camcorders), web sharing websites (like YouTube and Vimeo), and web plug-ins (like Flash and Silverlight). .mp4 read more..

  • Page - 172

    HTML5: THE MISSING MANUAL, SECOND EDITION 152 UNDERSTANDING THE HTML5 MEDIA FORMATS UP TO SPEED MIME Types and Why to Use Them A MIME type (sometimes called a content type) is a piece of information that identifies the type of content in a web re- source. For example, the MIME type of a web page is text/html. Before a web server sends a read more..

  • Page - 173

    CHAPTER 5: AUDIO AND VIDEO 153 UNDERSTANDING THE HTML5 MEDIA FORMATS Browser Support for Media Formats The format headaches in HTML5 have a long history. The conflict is fueled by the different needs of browser makers. Small companies, like Mozilla (the creators of Firefox) and Opera (the creators of the Opera browser) don’t want to pay stiff li- read more..

  • Page - 174

    HTML5: THE MISSING MANUAL, SECOND EDITION 154 FALLBACKS: HOW TO PLEASE EVERY BROWSER usage. To make mobile-friendly videos, you should encode them with lower quality settings and, possibly, with a lower resolution.  TIP  As a general rule of thumb, if you want a video to be playable on a mobile device, you should encode it using the H.264 Baseline read more..

  • Page - 175

    CHAPTER 5: AUDIO AND VIDEO 155 FALLBACKS: HOW TO PLEASE EVERY BROWSER Conscientious web developers use both types of fallback. More time-constrained (or lazier) web developers sometimes omit the format fallback, in order to eliminate the work of re-encoding their video files. After all, the Opera browser (the lone desktop browser that doesn’t support read more..

  • Page - 176

    HTML5: THE MISSING MANUAL, SECOND EDITION 156 FALLBACKS: HOW TO PLEASE EVERY BROWSER  NOTE  Just because a browser believes it supports a specific type of audio or video doesn’t necessarily mean it can play it. For example, you may have used an insanely high bitrate, or a strange codec in a recognized container format. You can deal with issues like these by read more..

  • Page - 177

    CHAPTER 5: AUDIO AND VIDEO 157 FALLBACKS: HOW TO PLEASE EVERY BROWSER Adding a Flash Fallback The format fallback system has a key limitation: It works only on browsers that understand the <audio> and <video> elements (which is almost every browser in circulation today, except IE 8). To get your pages to work on non-HTML5 browsers, read more..

  • Page - 178

    HTML5: THE MISSING MANUAL, SECOND EDITION 158 FALLBACKS: HOW TO PLEASE EVERY BROWSER Here’s an example that inserts the popular Flowplayer Flash ( http://flash.flowplayer.org) into an HTML5 <video> element: <video controls width="700" height="400"> <source src="beach.mp4" type="video/mp4"> <source src="beach.webm" read more..

  • Page - 179

    CHAPTER 5: AUDIO AND VIDEO 159 FALLBACKS: HOW TO PLEASE EVERY BROWSER FIGURE 5-5 One video, served three ways: in IE 9 (top), in Firefox (middle), and in IE 7, with Flash (bottom). read more..

  • Page - 180

    HTML5: THE MISSING MANUAL, SECOND EDITION 160 CONTROLLING YOUR PLAYER WITH JAVASCRIPT Interestingly, there’s another way to implement a Flash fallback. The examples you’ve seen so far use HTML5 with a Flash fallback, which gives everybody HTML5 video (or audio) except for people with older browsers, who get Flash. However, you can invert this approach and use read more..

  • Page - 181

    CHAPTER 5: AUDIO AND VIDEO 161 CONTROLLING YOUR PLAYER WITH JAVASCRIPT That’s about the most you can do with the <audio> and <video> elements if you stick to markup only. But both elements have an extensive JavaScript object model, which lets you control playback with code. In fact, you can even adjust some de- tails—like playback read more..

  • Page - 182

    HTML5: THE MISSING MANUAL, SECOND EDITION 162 CONTROLLING YOUR PLAYER WITH JAVASCRIPT This example combines a background music track with sound effects. The back- ground music track is the easiest part. To create it, you start by adding an invisible <audio> element to your page, like this: <audio id="backgroundMusic" loop> <source read more..

  • Page - 183

    CHAPTER 5: AUDIO AND VIDEO 163 CONTROLLING YOUR PLAYER WITH JAVASCRIPT A better approach is to use a group of <audio> elements, one for each sound. Here’s an example: <audio id="audio1"> <source src="boing1.mp3" type="audio/mp3"> <source src="boing1.wav" type="audio/wav"> </audio> <audio id="audio2"> read more..

  • Page - 184

    HTML5: THE MISSING MANUAL, SECOND EDITION 164 CONTROLLING YOUR PLAYER WITH JAVASCRIPT  TIP  To get an idea of the noise this page causes with its background music and sound effects, visit the try-out site at http://prosetech.com/html5. This example works well, but what if you want to have a much larger range of audio effects? The easiest choice is to create read more..

  • Page - 185

    CHAPTER 5: AUDIO AND VIDEO 165 CONTROLLING YOUR PLAYER WITH JAVASCRIPT FIGURE 5-7 Making a custom HTML5 video player is easy (making it pretty is not). This example includes the standard playback buttons, a playback progress bar, and a few extra buttons that show off what JavaScript can do with the <video> element. These buttons trigger the following super-simple read more..

  • Page - 186

    HTML5: THE MISSING MANUAL, SECOND EDITION 166 CONTROLLING YOUR PLAYER WITH JAVASCRIPT in a hurry. Similarly, a playbackRate of 0.5 plays video at half normal speed, and a playbackRate of -1 should play video at normal speed, backward, but browsers have trouble smoothly implementing this behavior. function speedUp() { video.play(); video.playbackRate read more..

  • Page - 187

    CHAPTER 5: AUDIO AND VIDEO 167 CONTROLLING YOUR PLAYER WITH JAVASCRIPT background: steelblue; text-align: center; } When video playback is under way, the <video> element triggers the onTimeUpdate event continuously. You can react to this event to update the playback bar: <video id="videoPlayer" ontimeupdate="progressUpdate()"> <source read more..

  • Page - 188

    HTML5: THE MISSING MANUAL, SECOND EDITION 168 CONTROLLING YOUR PLAYER WITH JAVASCRIPT Most JavaScript media players (including VideoJS and jPlayer) have built-in Flash fallbacks, which saves you from needing to find a separate Flash player. And jPlayer includes its own handy playlist feature, which lets you queue up a whole list of audio and video files read more..

  • Page - 189

    CHAPTER 5: AUDIO AND VIDEO 169 VIDEO CAPTIONS Then you use the exact same <video> element you’d normally use, with the mul- tiple source elements and Flash fallback. (The VideoJS player sample code has the Flowplayer already slotted in for the Flash fallback, but you can remove it and use a different Flash player instead.) In fact, the only read more..

  • Page - 190

    HTML5: THE MISSING MANUAL, SECOND EDITION 170 VIDEO CAPTIONS FIGURE 5-9 The subtitles in this video appear in their usual place: centered, and near the bottom of the video window. Timed Text Tracks and WebVTT In technical video speak, a subtitle is a caption that appears superimposed on a video, and a sequence of subtitles is a timed text track. There are read more..

  • Page - 191

    CHAPTER 5: AUDIO AND VIDEO 171 VIDEO CAPTIONS WEBVTT 00:00:05.000 --> 00:00:10.000 This caption appears 5 seconds in and lingers until the 10 second mark. 00:01:00.000 --> 00:01:10.000 Now 1 minute has passed. Think about that for 10 seconds. 00:01:10.000 --> 00:01:15.000 This caption appears immediately after the second caption disappears. 00:01:30.000 --> 00:01:35.000 read more..

  • Page - 192

    HTML5: THE MISSING MANUAL, SECOND EDITION 172 VIDEO CAPTIONS FIGURE 5-10 To use the Caption Maker, you must first point it to a video file that’s already on the Web (type in the URL and click Load). While you’re playing the video, it’s easy to make a quick caption (type it in the box under the video window and then click Save). Then, when you’re read more..

  • Page - 193

    CHAPTER 5: AUDIO AND VIDEO 173 VIDEO CAPTIONS The kind attribute describes the type of content in your captions. The HTML5 specification gives you five choices, but only two result in the pop-up captions you expect. Specify subtitles if your text consists of transcriptions or translations of dialogue), or captions if your text includes read more..

  • Page - 194

    HTML5: THE MISSING MANUAL, SECOND EDITION 174 VIDEO CAPTIONS Browser Support for Video Captions Browsers have been slow to support the <track> element. At this writing, Firefox doesn’t support it at all, but the developers at Mozilla plan to include it in the future. Table 5-4 details the current state of affairs. FIGURE 5-11 Browsers that support read more..

  • Page - 195

    CHAPTER 5: AUDIO AND VIDEO 175 VIDEO CAPTIONS Fortunately, you can use the <track> element without worry. Browsers that don’t support it simply ignore it, without a hiccup. If you need a way to provide captions that work on every HTML5 browser, there’s an easy workaround. You can use the <track> element as you would normally, in read more..

  • Page - 196

    read more..

  • Page - 197

    177 CHAPTER 6 It would be ludicrous to build a modern website without CSS. The standard is fused into the fabric of the Web almost as tightly as HTML. Whether you’re laying out pages, building interactive buttons and menus, or just making things look pretty, CSS is a fundamental tool. In fact, as HTML has increasingly shifted its focus read more..

  • Page - 198

    HTML5: THE MISSING MANUAL, SECOND EDITION 178 USING CSS3 TODAY features: transforms and transparency.) Finally, you’ll learn how to jazz up ordinary text with a rich variety of web fonts. But first, before you get to any of these hot new features, it’s time to consider how you can plug in the latest and most stylin’ features without read more..

  • Page - 199

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 179 USING CSS3 TODAY The idea behind this strategy is to use CSS3 to add fine touches that won’t be missed by people using less-capable browsers. One example is the border-radius property that you can use to gently round the corners of a floating box. Here’s an example: header { read more..

  • Page - 200

    HTML5: THE MISSING MANUAL, SECOND EDITION 180 USING CSS3 TODAY  TIP  When it comes to CSS3, Internet Explorer is the straggler. There’s a militant minority of web designers who believe that web designers should ignore backward browsers like IE 8 and start using CSS3 features as soon as other browsers support them. Otherwise, who will keep pressure on Microsoft read more..

  • Page - 201

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 181 USING CSS3 TODAY don’t support multicolored borders, the thick border is an eyesore, no matter what single color you use. FIGURE 6-3 Top: In browsers that don’t understand CSS3, the stylishBox rule paints a yellow background. Bottom: In browsers that do understand CSS3, the yellow background is replaced read more..

  • Page - 202

    HTML5: THE MISSING MANUAL, SECOND EDITION 182 USING CSS3 TODAY /* Settings for browsers that don't support border-radius. */ .no-borderradius header { border: 5px #336699 double; } So how does this nifty trick work? When you use Modernizr in a page, you begin by adding the class="no-js" attribute to the root <html> element: <html read more..

  • Page - 203

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 183 USING CSS3 TODAY Browser-Specific Styles with Vendor Prefixes When the creators of CSS develop new features, they often run into a chicken-and- egg dilemma. In order to perfect the feature, they need feedback from browser makers and web designers. But in order to get this feedback, browser makers and read more..

  • Page - 204

    HTML5: THE MISSING MANUAL, SECOND EDITION 184 BUILDING BETTER BOXES Clearly, when dealing with the less mature parts of CSS3, you need some bloated style sheet rules. The obvious question for every web designer is “When do I need to use vendor prefixes, and when is it safe to use the ordinary, unprefixed property or function name?” You read more..

  • Page - 205

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 185 BUILDING BETTER BOXES FIGURE 6-4 If you need to use a prefix, the “Can I use…” website lets you know in a tiny yellow text bubble. For example, the CSS3 transforms feature doesn’t need a vendor prefix in the latest versions of Firefox or IE, but it does in all other browsers. GEM IN THE ROUGH read more..

  • Page - 206

    HTML5: THE MISSING MANUAL, SECOND EDITION 186 BUILDING BETTER BOXES Your first option is to use the rgba() color function, which accepts four numbers. The first three values are the red, green, and blue components of the color, from 0 to 255. The final value is the alpha, a fractional value number from 0 (fully transpar- ent) to 1 read more..

  • Page - 207

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 187 BUILDING BETTER BOXES FIGURE 6-5 This page serves up semitransparency two different ways: to fade out a picture (using the opacity property) and to let the background show through a box (using a background color created with the rgba() function). Rounded Corners You’ve already learned about the border-radius read more..

  • Page - 208

    HTML5: THE MISSING MANUAL, SECOND EDITION 188 BUILDING BETTER BOXES .roundedBox { background: yellow; border-top-left-radius: 150px 30px; border-top-right-radius: 150px 30px; } Figure 6-6 shows some examples. FIGURE 6-6 A clever application of border-radius can create virtu- ally any sort of curve. Backgrounds One shortcut to attractive backgrounds and borders is to use read more..

  • Page - 209

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 189 BUILDING BETTER BOXES This first step is to supply a list with any number of images, which you use to set the background-image property. You can then position each image and control whether it repeats, using the background-position and background-repeat properties. The trick is to make sure that the read more..

  • Page - 210

    HTML5: THE MISSING MANUAL, SECOND EDITION 190 BUILDING BETTER BOXES  NOTE  If browsers don’t support multiple backgrounds, they’ll completely ignore your attempt to set the background. To avoid this problem, start by setting the background or background-image property with a fallback color or picture. Then, attempt to set multiple backgrounds by setting read more..

  • Page - 211

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 191 BUILDING BETTER BOXES The two properties that make shadows work are box-shadow and text-shadow. Here’s a basic box shadow example: .shadowedBox { border: thin #336699 solid; border-radius: 25px; box-shadow: 5px 5px 10px gray; } The first two values set the horizontal and vertical offset of the read more..

  • Page - 212

    HTML5: THE MISSING MANUAL, SECOND EDITION 192 BUILDING BETTER BOXES  NOTE  Many web gradients are faked with background images. But CSS3 lets you define the gradient you want and gets the browser to do the work. The advantage is fewer image files to schlep around and the ability to create gradients that seamlessly resize themselves to fill any amount of read more..

  • Page - 213

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 193 BUILDING BETTER BOXES Similarly, you can replace top with left to go from one side to another. Or use both to blend diagonally from the top-left corner: background: linear-gradient(from top left, white, lightblue) If you want multiple-color bands, you simply supply a list of colors. Here’s how read more..

  • Page - 214

    HTML5: THE MISSING MANUAL, SECOND EDITION 194 BUILDING BETTER BOXES background: radial-gradient(circle, white, lightblue); Once again, you need to add a -webkit- version of the function to be safe: background: -webkit-radial-gradient(circle, yellow, green); Replace the word circle with ellipse if you want to stretch your gradient out into an oblong shape to read more..

  • Page - 215

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 195 CREATING EFFECTS WITH TRANSITIONS The following gradient is different. It keeps the yellow in the center, but sets the green to kick in at the 10% mark. After that, the gradient repeats, starting with the yellow color again. The result is a striped effect of blurry yellow and green lines. background: read more..

  • Page - 216

    HTML5: THE MISSING MANUAL, SECOND EDITION 196 CREATING EFFECTS WITH TRANSITIONS  TIP  If you’re the last web developer on earth who hasn’t rolled your own hover button, you can find a detailed tutorial in Creating a Website: The Missing Manual, or in an online article at www.elated.com/articles/ css-rollover-buttons. Great as they are, pseudo-classes aren’t read more..

  • Page - 217

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 197 CREATING EFFECTS WITH TRANSITIONS Here’s a button that uses these style rules: <button class="slickButton">Hover Here!</a> This approach is all well and good, but it lacks a certain finesse. To smooth out the green-to-yellow color change, you can create a CSS3 transition using the transition property. read more..

  • Page - 218

    HTML5: THE MISSING MANUAL, SECOND EDITION 198 CREATING EFFECTS WITH TRANSITIONS -webkit-transition: all 0.5s; transition: all 0.5s; Right now, transitions work in the latest version of every browser. Old versions of Internet Explorer (IE 9 and before) don’t have any transition support, and vendor prefixes won’t help. However, this lack of support read more..

  • Page - 219

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 199 CREATING EFFECTS WITH TRANSITIONS Fortunately, it’s easy to create a JavaScript-powered transition. As with an ordinary transition, you begin by creating two style rules, one for your element’s initial state, and one for its transitioned state. Then you add the JavaScript code that finds your read more..

  • Page - 220

    HTML5: THE MISSING MANUAL, SECOND EDITION 200 CREATING EFFECTS WITH TRANSITIONS FIGURE 6-11 Initially, the image with the night skyline is completely transparent (top). But click the To Night button and the night image fades in, gradu- ally blotting out the day skyline (bottom). The page markup places both images into a <div>, taki ng care to apply the read more..

  • Page - 221

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 201 CREATING EFFECTS WITH TRANSITIONS The final step is to add the code that reacts to the button clicks, finds the nighttime image, and switches its style: function toNight() { var nightImage = document.getElementById("nightImage"); nightImage.className = "solid"; } function toDay() { read more..

  • Page - 222

    HTML5: THE MISSING MANUAL, SECOND EDITION 202 CREATING EFFECTS WITH TRANSITIONS .rotatedElement { -ms-transform: rotate(45deg); -webkit-transform: rotate(45deg); transform: rotate(45deg); } POWER USERS’ CLINIC Making More Natural Transitions The transition property is an all-in-one property that combines several details. So far, you’ve seen how to give a read more..

  • Page - 223

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 203 CREATING EFFECTS WITH TRANSITIONS Table 6-2 lists all the two-dimensional transform functions you can use. To remove all your transforms, set the transform property to none.  NOTE  Transforms don’t affect other elements or the layout of your web page. For example, if you enlarge an element with a transform, read more..

  • Page - 224

    HTML5: THE MISSING MANUAL, SECOND EDITION 204 CREATING EFFECTS WITH TRANSITIONS  NOTE  When you get tired of moving an element around in two dimensions, you can use 3-D transforms to move, rotate, and warp it in three-dimensional space. You’ll find several good, interactive examples of 3-D transforms at http://tinyurl.com/3d-transitions. POWER USERS’ CLINIC How to read more..

  • Page - 225

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 205 CREATING EFFECTS WITH TRANSITIONS <div class="gallery"> <img src="bunny.jpg"> <img src="cat.jpg"> <img src="dog.jpg"> <img src="platypus.jpg"> <img src="goose.jpg"> </div> Here’s the style for the <div> that holds all the images: .gallery { read more..

  • Page - 226

    HTML5: THE MISSING MANUAL, SECOND EDITION 206 WEB FONTS -ms-transition: all 1s; -webkit-transition: all 1s; transition: all 1s; background: white; } Now the picture rotates and grows over a time span of 1 second. Move the mouse away, and it takes another second to shrink back to its original position. Web Fonts With all its pizzazzy new read more..

  • Page - 227

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 207 WEB FONTS The following sections walk you through these essential steps. FIGURE 6-13 This revised version of the apocalyptic page combines a hodgepodge of four fonts. All of these fonts are free, and you’ll learn how to get them for yourself from Font Squirrel on page 209. Web Font Formats Although all current read more..

  • Page - 228

    HTML5: THE MISSING MANUAL, SECOND EDITION 208 WEB FONTS TABLE 6-3 Embedded font formats FORMAT DESCRIPTION USE WITH WOFF (Web Open Font Format) The single font format of the future. Newer browsers support it. Any browser that supports it, starting with Internet Explorer 9, Firefox 3.6, and Chrome 6. EOT (Embedded Open Type) A Microsoft-specific format that never caught on with read more..

  • Page - 229

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 209 WEB FONTS • Convert a desktop font you already have into a web font. This approach lets you use a font that you’ve already fallen in love with. It’s also great for consis- tency—for example, if you work in a company that already has a standard set of fonts that it uses in logos, memos, read more..

  • Page - 230

    HTML5: THE MISSING MANUAL, SECOND EDITION 210 WEB FONTS FIGURE 6-14 Font Squirrel gives you several options for font hunting, but the most effective way to find what you want is to browse by type (“Calligraphic,” “Novelty,” and “Retro,” for example). Best of all, most fonts are free to use wherever you want—on your personal computer to create read more..

  • Page - 231

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 211 WEB FONTS FREQUENTLY ASKED QUESTION Using a Font on Your Computer Can I use the same font for web work and printed documents? If you find a hot new font to use in your website, you can prob- ably put it to good use on your computer, too. For example, you might want to use it in an read more..

  • Page - 232

    HTML5: THE MISSING MANUAL, SECOND EDITION 212 WEB FONTS Once you know that you’re allowed to use a specific font, you can convert it us- ing Font Squirrel’s handy web font generator. To get there, click on the Webfont Generator tab near the top of the Font Squirrel site, or just surf directly to www. fontsquirrel.com/fontface/generator. Figure 6-16 read more..

  • Page - 233

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 213 WEB FONTS To use the Chantelli Antiqua font, you need to copy all the Chantelli_Antiqua-webfont files to the same folder as your web page. Then you need to register the font so that it’s available for use in your style sheet. To do that, you use a complex @font- face rule at the read more..

  • Page - 234

    HTML5: THE MISSING MANUAL, SECOND EDITION 214 WEB FONTS Once you register an embedded font using the @font-face feature, you can use it in any style sheet. Simply use the familiar font-family property, and refer to the font family name you specified with @font-face (in line 2). Here’s an example that leaves out the full @font-face details: read more..

  • Page - 235

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 215 WEB FONTS FIGURE 6-17 Google has a relentlessly expanding selection of fonts. When you’re looking for a font, you’ll probably want to tweak the font list’s sorting and filtering options (circled). For example, you can sort alphabetically or put the most popular fonts first, and you can filter out just read more..

  • Page - 236

    HTML5: THE MISSING MANUAL, SECOND EDITION 216 WEB FONTS <link href="http://fonts.googleapis.com/css?family=Metrophobic" rel="stylesheet"> This style sheet registers the font, using @font-face, so you don’t have to. Best of all, Google provides the font files, so you don’t need to upload anything extra to your website.  NOTE  Remember to put read more..

  • Page - 237

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 217 WEB FONTS Putting Text in Multiple Columns Fancy fonts aren’t the only innovation CSS3 has for displaying text. It also adds a module for multicolumn text, which gives you a flexible, readable way to deal with lengthy content. Using multiple columns is almost effortless, and you have two read more..

  • Page - 238

    HTML5: THE MISSING MANUAL, SECOND EDITION 218 WEB FONTS FIGURE 6-18 In a narrow window (top), Firefox can accommodate just one column. But widen the window, and you’ll get as many more as can fit (bottom). read more..

  • Page - 239

    CHAPTER 6: FANCY FONTS AND EFFECTS WITH CSS3 219 WEB FONTS CSS3 provides a few more properties for tailoring the look of your columns. You can adjust the size of the spacing between columns with column-gap. You can also add a vertical line to separate them with column-rule, which accepts a thickness, border style, and color (just like the border read more..

  • Page - 240

    HTML5: THE MISSING MANUAL, SECOND EDITION 220 WEB FONTS FIGURE 6-19 This tweaked-up multicolumn page adds a rule between columns and lets figures span multiple columns. read more..

  • Page - 241

    221 CHAPTER 7 When web designers first started putting their content into HTML pages, they faced a challenge. Whereas print designers could rely on certain as- sumptions about how their documents would be arranged on paper and how they would be read by their audiences, the online world was loose and lawless. Depending on the read more..

  • Page - 242

    HTML5: THE MISSING MANUAL, SECOND EDITION 222 RESPONSIVE DESIGN: THE BASICS the navigation links from the top of a page to its side. This sort of adaptation is part of a wildly popular web design philosophy called responsive design, which you’ll explore in this chapter. Responsive Design: The Basics The problem of varying window sizes has been around read more..

  • Page - 243

    CHAPTER 7: RESPONSIVE WEB DESIGN WITH CSS3 223 RESPONSIVE DESIGN: THE BASICS body { margin: 0px; } But the style rules for a proportionately sized layout would look like this: .leftColumn { width: 28.6%; float: left; } .rightColumn { width: 71.4%; float: left; } body { margin: 0px; } Here, the left column has a width of 28.6%, so read more..

  • Page - 244

    HTML5: THE MISSING MANUAL, SECOND EDITION 224 RESPONSIVE DESIGN: THE BASICS margin: 5px; float: left; } .rightColumn { width: 68%; margin: 5px; float: left; } These two columns occupy a combined 95%, leaving an extra 5% for the margin space. This is enough for mid- to large-sized windows, but if you size the window small enough, read more..

  • Page - 245

    CHAPTER 7: RESPONSIVE WEB DESIGN WITH CSS3 225 RESPONSIVE DESIGN: THE BASICS .leftColumn { width: 27%; margin-left: 1.66%; margin-right: 1.66%; background: #FFFFCC; float: left; } .rightColumn { width: 68%; margin-right: 1.66%; background: #CCFFCC; float: left; } Figure 7-2 shows the solution, with both margins and columns sized read more..

  • Page - 246

    HTML5: THE MISSING MANUAL, SECOND EDITION 226 RESPONSIVE DESIGN: THE BASICS Borders present a similar problem. If you add borders to your columns, the extra space they require will break your layout in the same way as the fixed margins shown in Figure 7-1. In this situation, you can’t solve the problem with proportional measurements, because read more..

  • Page - 247

    CHAPTER 7: RESPONSIVE WEB DESIGN WITH CSS3 227 RESPONSIVE DESIGN: THE BASICS img { max-width: 100%; } As always, the 100% is relative to the element’s container. In this case, that’s the column that contains the image, not the whole page. Now your image can grow until it reaches its full size or until it meets the boundaries of its read more..

  • Page - 248

    HTML5: THE MISSING MANUAL, SECOND EDITION 228 RESPONSIVE DESIGN: THE BASICS One limitation of fluid images is that the browser needs to download the full-sized image file no matter what size the image is displayed at. This wastes a small amount of time and bandwidth, which is inconvenient for mobile devices. Sadly, CSS can’t correct this read more..

  • Page - 249

    CHAPTER 7: RESPONSIVE WEB DESIGN WITH CSS3 229 RESPONSIVE DESIGN: THE BASICS h1 { font-size: 2em } Experienced web developers don’t stop there. Instead, they use ems for all other fixed measurements in their layouts. For example, if you have a border or a bit of margin or padding space deep inside your layout, you’re better off to read more..

  • Page - 250

    HTML5: THE MISSING MANUAL, SECOND EDITION 230 RESPONSIVE DESIGN: THE BASICS  NOTE  In most layouts, the chief benefit of using ems for borders, margins, and padding is that it prevents these elements from being too large in tiny windows and dominating your layout on mobile devices. FEATURE FROM THE FUTURE CSS3: When an Em Becomes a Rem There’s one quirk that faces read more..

  • Page - 251

    CHAPTER 7: RESPONSIVE WEB DESIGN WITH CSS3 231 ADAPTING YOUR LAYOUT WITH MEDIA QUERIES The viewport technique is a bit of a tradeoff. It ensures that the page looks more like it would on a desktop browser, but it also makes most ordinary text illegible. It reduces the need to scroll back and forth, but it increases the need to zoom in read more..

  • Page - 252

    HTML5: THE MISSING MANUAL, SECOND EDITION 232 ADAPTING YOUR LAYOUT WITH MEDIA QUERIES FIGURE 7-4 Left: The iPhone’s automatic rescaling treats this fluid layout like a desktop-optimized web page. As a result, its text is unreadable without zooming. Right: Turn off the scaling, and you see your page as it truly is. The next step is to simplify the read more..

  • Page - 253

    CHAPTER 7: RESPONSIVE WEB DESIGN WITH CSS3 233 ADAPTING YOUR LAYOUT WITH MEDIA QUERIES an ultra-widescreen desktop computer to an iPhone—without altering a single line of HTML. The Anatomy of a Media Query Media queries work by latching onto a key detail about the device that’s viewing your page (like its size, resolution, color capabilities, and read more..

  • Page - 254

    HTML5: THE MISSING MANUAL, SECOND EDITION 234 ADAPTING YOUR LAYOUT WITH MEDIA QUERIES FEATURE NAME VALUE COMMONLY USED TO… device-height min-device-height max-device-height The full height of the screen or page. Adjust the layout to specifically target different devices, like smartphones. orientation One of two values: landscape or portrait. Change the layout for different orientations on read more..

  • Page - 255

    CHAPTER 7: RESPONSIVE WEB DESIGN WITH CSS3 235 ADAPTING YOUR LAYOUT WITH MEDIA QUERIES limit. For example, the following media query creates a block of conditional styles that spring into action when the width of the browser window is 480 pixels or less: @media (max-width: 480px) { ... }  TIP  Right now, the most popular media features are read more..

  • Page - 256

    HTML5: THE MISSING MANUAL, SECOND EDITION 236 ADAPTING YOUR LAYOUT WITH MEDIA QUERIES Building a Mobile-Friendly Layout With media queries, you have the essential building blocks you need to create a website that looks just as respectable in a smartphone browser as a desktop browser. All you need to do is apply them. Figure 7-5 shows a revamped read more..

  • Page - 257

    CHAPTER 7: RESPONSIVE WEB DESIGN WITH CSS3 237 ADAPTING YOUR LAYOUT WITH MEDIA QUERIES columns compress themselves, they won’t fit cleanly in a tiny window. To correct this oversight, you need to use a media query. Before you crack open your style sheet, you need to consider what the mobile ver- sion of your site should look like. read more..

  • Page - 258

    HTML5: THE MISSING MANUAL, SECOND EDITION 238 ADAPTING YOUR LAYOUT WITH MEDIA QUERIES .Content { float: left; width: 78%; } The sidebar is floated on the left with a width of 22%. The content is floated next to it and given a width of 78%. Because the layout stops working at small widths, it makes sense to use the popular max-width read more..

  • Page - 259

    CHAPTER 7: RESPONSIVE WEB DESIGN WITH CSS3 239 ADAPTING YOUR LAYOUT WITH MEDIA QUERIES This example needs one more adjustment. In the original version of the page, the NavSidebar section is defined before the Content section in the HTML markup. This lets you float them both on the left side, and makes sure the NavSidebar is on the left. read more..

  • Page - 260

    HTML5: THE MISSING MANUAL, SECOND EDITION 240 ADAPTING YOUR LAYOUT WITH MEDIA QUERIES POWER USERS’ CLINIC Hiding and Replacing Sections If you’re ambitious, there are many more changes you can make to differentiate the mobile version of your site from its full-size incarnation. For example, you can use the CSS dis- play property to hide and read more..

  • Page - 261

    CHAPTER 7: RESPONSIVE WEB DESIGN WITH CSS3 241 ADAPTING YOUR LAYOUT WITH MEDIA QUERIES In this case, if the browser window is 380 pixels, exactly two sets of styles will apply: the standard styles and the styles in the final @media block. Whether this approach simplifies your life or complicates it depends on what you’re trying to accomplish. read more..

  • Page - 262

    HTML5: THE MISSING MANUAL, SECOND EDITION 242 ADAPTING YOUR LAYOUT WITH MEDIA QUERIES The browser will download the second style sheet ( small_styles.css) with the page but won’t apply it unless the browser width falls under the maximum. As in the previous example, the new styles will override the styles you already have in place. In some cases, you read more..

  • Page - 263

    CHAPTER 7: RESPONSIVE WEB DESIGN WITH CSS3 243 ADAPTING YOUR LAYOUT WITH MEDIA QUERIES If you’re a hardware geek, this rule may have raised a red flag. After all, modern mobile devices use tiny, super-high-resolution screens. For example, the iPhone 5 crams a grid of 640 x 1136 pixels into view at once. You might think you’d need larger read more..

  • Page - 264

    HTML5: THE MISSING MANUAL, SECOND EDITION 244 ADAPTING YOUR LAYOUT WITH MEDIA QUERIES <link rel="stylesheet" media="(max-device-width: 768px) and (orientation: portrait)" href="iPad_portrait.css"> <link rel="stylesheet" media="(max-device-width: 768px) and (orientation: landscape)" href="iPad_landscape.css"> Of course, this rule isn’t limited to iPads. read more..

  • Page - 265

    245 CHAPTER 8 As you learned in Chapter 1, one of HTML5’s goals is to make it easier to put rich applications inside otherwise ordinary web pages. In this case, the word “rich” do esn’t have anything to do with your bank account. Instead, a rich application is one that’s decked out with slick graphics, interactive features, and read more..

  • Page - 266

    HTML5: THE MISSING MANUAL, SECOND EDITION 246 GETTING STARTED WITH THE CANVAS  NOTE  For some developers, the canvas will be indispensable. For others, it will just be an interesting diver- sion. (And for some, it may be interesting but still way too much work compared with a mature programming platform like Flash.) But one thing is certain: This straightforward drawing read more..

  • Page - 267

    CHAPTER 8: BASIC DRAWING WITH THE CANVAS 247 GETTING STARTED WITH THE CANVAS FIGURE 8-1 Every canvas begins as an empty rectangle somewhere on a web page. To put even a single line inside, you need to write some JavaScript code. Once you have the canvas object, you can take the second essential step. You use the canvas object’s getContext() method to read more..

  • Page - 268

    HTML5: THE MISSING MANUAL, SECOND EDITION 248 GETTING STARTED WITH THE CANVAS <style> canvas { border: 1px dashed black; } </style> <script> window.onload = function() { var canvas = document.getElementById("drawingCanvas"); var context = canvas.getContext("2d"); // (Put your fabulous drawing code here.) }; read more..

  • Page - 269

    CHAPTER 8: BASIC DRAWING WITH THE CANVAS 249 GETTING STARTED WITH THE CANVAS FIGURE 8-2 As with every other HTML element, the canvas designates its top-left corner as the point (0,0). As you move right, the x-value increases, and as you move down, the y- value increases. If a canvas is 500 x 300 pixels, then the bottom-right corner is point (500, 300). read more..

  • Page - 270

    HTML5: THE MISSING MANUAL, SECOND EDITION 250 GETTING STARTED WITH THE CANVAS You use strokeStyle to set the color of your lines. You can use an HTML color name, an HTML color code, or the CSS rgb() function which lets you assemble a color from red, green, and blue components. (This approach is useful because most drawing and painting read more..

  • Page - 271

    CHAPTER 8: BASIC DRAWING WITH THE CANVAS 251 GETTING STARTED WITH THE CANVAS // Draw the third line, with a square cap. context.beginPath(); context.moveTo(10,190); context.lineTo(400,190); context.lineCap = "square"; context.stroke(); This example introduces one new feature: the beginPath() method of the drawing context. When you call beginPath(), you start a new, read more..

  • Page - 272

    HTML5: THE MISSING MANUAL, SECOND EDITION 252 GETTING STARTED WITH THE CANVAS context.moveTo(250,50); context.lineTo(50,250); context.lineTo(450,250); context.lineTo(250,50); context.lineWidth = 10; context.strokeStyle = "red"; context.stroke(); But if you want to fill that triangle, the stroke() method won’t help you. Instead, you need to close the path by calling read more..

  • Page - 273

    CHAPTER 8: BASIC DRAWING WITH THE CANVAS 253 GETTING STARTED WITH THE CANVAS  NOTE  When drawing connecting line segments (like the three sides of this triangle), you can set the drawing context’s lineJoin property to round or bevel the edges (by using the values round or bevel—the default is mitre). FIGURE 8-4 To create a closed shape like this read more..

  • Page - 274

    HTML5: THE MISSING MANUAL, SECOND EDITION 254 GETTING STARTED WITH THE CANVAS Curved Lines If you want something more impressive than lines and rectangles (and who doesn’t?), you’ll need to understand four methods that can really throw you for a curve: arc(), arcTo(), bezierCurveTo(), and quadraticCurveTo(). All of these methods draw curved lines in different read more..

  • Page - 275

    CHAPTER 8: BASIC DRAWING WITH THE CANVAS 255 GETTING STARTED WITH THE CANVAS // Use this information to draw the arc. context.arc(centerX, centerY, radius, startingAngle, endingAngle); context.stroke(); Or, call closePath() before you call stroke() to add a straight line between the two ends of the arc. This creates a closed semi-circle. Incidentally, a circle is read more..

  • Page - 276

    HTML5: THE MISSING MANUAL, SECOND EDITION 256 GETTING STARTED WITH THE CANVAS var endPointX = 365; var endPointY = 133; // Draw the curve. context.bezierCurveTo(control1_x, control1_y, control2_x, control2_y, endPointX, endPointY); context.stroke(); FIGURE 8-6 A Bézier curve has t wo control points. The start of the curve runs parallel to the first control point. The end of the read more..

  • Page - 277

    CHAPTER 8: BASIC DRAWING WITH THE CANVAS 257 GETTING STARTED WITH THE CANVAS Or you could call fillRect() three times, with the same point, but shift the coordi- nate system each time so the square actually ends up in three different spots, like so: var canvas = document.getElementById("drawingCanvas"); var context = read more..

  • Page - 278

    HTML5: THE MISSING MANUAL, SECOND EDITION 258 GETTING STARTED WITH THE CANVAS FREQUENTLY ASKED QUESTION Canvas Drawing for Math-Phobes How do I get all the shapes with none of the headaches? If you’re hoping to use the canvas to create eye-catching graphics, but you don’t want to pick up a degree in geometry, you might be a bit read more..

  • Page - 279

    CHAPTER 8: BASIC DRAWING WITH THE CANVAS 259 GETTING STARTED WITH THE CANVAS bigger or smaller), a rotate transform (which lets you turn the coordinate system around), and a matrix transform (which lets you stretch and warp the coordinate system in virtually any way—provided you understand the complex matrix math that underpins the visual effect read more..

  • Page - 280

    HTML5: THE MISSING MANUAL, SECOND EDITION 260 GETTING STARTED WITH THE CANVAS  TIP  You can use the drawing context’s save() method to save the current state of the coordinate system. Later on, you can use the restore() method to return to your previous saved state. You might want to call save() before you’ve applied any transforms, so you can read more..

  • Page - 281

    CHAPTER 8: BASIC DRAWING WITH THE CANVAS 261 GETTING STARTED WITH THE CANVAS // Remember to call beginPath() before adding a new shape. // Otherwise, the outlines of both shapes will // be merged together in an unpredictable way. context.beginPath(); // Give the triangle a transparent fill. context.fillStyle = "rgba(100,150,185,0.5)"; // Now draw the triangle. read more..

  • Page - 282

    HTML5: THE MISSING MANUAL, SECOND EDITION 262 GETTING STARTED WITH THE CANVAS So which approach is better? If you need just a single transparent color, use rgba(). If you need to paint a variety of shapes with different colors, and they all need the same level of transparency, use globalAlpha. The globalAlpha property is also useful if you want read more..

  • Page - 283

    CHAPTER 8: BASIC DRAWING WITH THE CANVAS 263 BUILDING A BASIC PAINT PROGRAM To change the current composite operation that the canvas uses, simply set the drawing context’s globalCompositeOperation property before you draw the second shape, like this: context.globalCompositeOperation = "xor"; For example, to create the source-atop combination shown in the read more..

  • Page - 284

    HTML5: THE MISSING MANUAL, SECOND EDITION 264 BUILDING A BASIC PAINT PROGRAM FIGURE 8-11 To express yourself with this paint program, just pick a pen color, pick a pen thickness, and scribble away with the mouse. Preparing to Draw First, when the page loads, the code grabs the canvas object and attaches functions that will handle several JavaScript read more..

  • Page - 285

    CHAPTER 8: BASIC DRAWING WITH THE CANVAS 265 BUILDING A BASIC PAINT PROGRAM // Attach the events that you need for drawing. canvas.onmousedown = startDrawing; canvas.onmouseup = stopDrawing; canvas.onmouseout = stopDrawing; canvas.onmousemove = draw; }; To get started with the paint program, the person using the page chooses the pen color and pen read more..

  • Page - 286

    HTML5: THE MISSING MANUAL, SECOND EDITION 266 BUILDING A BASIC PAINT PROGRAM the code needs to keep track of the previously selected color so it can remove the solid border around that <img> element. The changeThickness() function performs an almost identical task, only it alters the lineWidth property to have the appropriate thickness: // Keep read more..

  • Page - 287

    CHAPTER 8: BASIC DRAWING WITH THE CANVAS 267 BUILDING A BASIC PAINT PROGRAM In order for the paint program to work properly, it needs to start drawing at the current position—that’s wh ere the mouse is hovering when the user clicks down. However, getting the right coordinates for this point is a bit tricky. The onMouseDown event provides coordinates read more..

  • Page - 288

    HTML5: THE MISSING MANUAL, SECOND EDITION 268 BUILDING A BASIC PAINT PROGRAM The save option is slightly more interesting, and you’ll consider it next. Saving the Picture in the Canvas When it comes to saving the picture in a canvas, there are countless options. First, you need to decide how you’re going to get the data. The canvas gives you read more..

  • Page - 289

    CHAPTER 8: BASIC DRAWING WITH THE CANVAS 269 BUILDING A BASIC PAINT PROGRAM At this point, you’re probably wondering what a data URL looks like. Technically, it’s a long string of base-64 encoded characters that starts with the text data:image/ png;base64. It looks like gobbledygook, but that’s OK, because it’s supposed to be readable by read more..

  • Page - 290

    HTML5: THE MISSING MANUAL, SECOND EDITION 270 BUILDING A BASIC PAINT PROGRAM  NOTE  Firefox has the built-in ability to save canvas content. Just right-click any canvas (not the image copy) and choose Save Image As. Other browsers, like Chrome and Internet Explorer, don’t offer this option. FIGURE 8-12 Here, the data URL is used to transmit information to read more..

  • Page - 291

    CHAPTER 8: BASIC DRAWING WITH THE CANVAS 271 BROWSER COMPATIBILITY FOR THE CANVAS GEM IN THE ROUGH Canvas-Based Paint Programs A paint program is one of the first examples that comes to mind when people start exercising their canvas-programming muscles. It’s thus no surprise that you can Google up many more paint program examples on read more..

  • Page - 292

    HTML5: THE MISSING MANUAL, SECOND EDITION 272 BROWSER COMPATIBILITY FOR THE CANVAS  NOTE  VML is a specification for creating line art and other illustrations using markup in an HTML document. It’s now been replaced by a similar, but better supported, standard called SVG (Scalable Vector Graphics), which browsers are just beginning to support. Today, VML still read more..

  • Page - 293

    CHAPTER 8: BASIC DRAWING WITH THE CANVAS 273 BROWSER COMPATIBILITY FOR THE CANVAS FlashCanvas also has a grown-up professional version called FlashCanvas Pro. It adds support for a few additional features, like global composite operations (page 262) and shadows (page 281). FlashCanvas Pro is free for noncommercial use (get it at http://flashcanvas.net/ download). read more..

  • Page - 294

    HTML5: THE MISSING MANUAL, SECOND EDITION 274 BROWSER COMPATIBILITY FOR THE CANVAS FREQUENTLY ASKED QUESTION Canvas Accessibility Is it possible to make the canvas more accessible? One of the key themes of HTML5, the semantic elements, and the past few chapters is accessibility—designing a page that provides information to assistive software, so it can read more..

  • Page - 295

    275 CHAPTER 9 The canvas is a huge, sprawling feature. In the previous chapter, you learned how to draw line art and even create a respectable drawing program in a few dozen lines of JavaScript. But the canvas has more up its sleeve than that. Not only can it show dynamic pictures and host paint programs, but it can also play read more..

  • Page - 296

    HTML5: THE MISSING MANUAL, SECOND EDITION 276 OTHER THINGS YOU CAN DRAW ON THE CANVAS your drawing increases, so does the code. It’s extremely unlikely that you’d write by hand all the code you need to create a finely detailed picture. Fortunately, you have other options. The drawing context isn’t limited to lines and curves—it also has read more..

  • Page - 297

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 277 OTHER THINGS YOU CAN DRAW ON THE CANVAS // Draw the image. (This could fail, because the picture // might not be downloaded yet.) context.drawImage(img, 0, 0); The problem here is that setting the src attribute starts an image download, but your code carries on without waiting for it to finish. The read more..

  • Page - 298

    HTML5: THE MISSING MANUAL, SECOND EDITION 278 OTHER THINGS YOU CAN DRAW ON THE CANVAS Slicing, Dicing, and Resizing an Image The drawImage() function accepts a few optional arguments that let you alter the way your image is painted on the canvas. First, if you want to resize the image, you can tack on the width and height you want, like this: read more..

  • Page - 299

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 279 OTHER THINGS YOU CAN DRAW ON THE CANVAS GEM IN THE ROUGH Drawing a Video Frame The first parameter of the drawImage() method is the image you want to draw. As you’ve seen, this can be an Image object you’ve just created, or an <img> element that’s elsewhere on read more..

  • Page - 300

    HTML5: THE MISSING MANUAL, SECOND EDITION 280 OTHER THINGS YOU CAN DRAW ON THE CANVAS context.textBaseline = "top"; context.fillStyle = "black"; context.fillText("I'm stuck in a canvas. Someone let me out!", 10, 10); You can put the text wherever you want, but you’re limited to a single line. If you want to draw multiple lines of text, you read more..

  • Page - 301

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 281 SHADOWS AND FANCY FILLS Shadows and Fancy Fills So far, when you’ve drawn lines and filled shapes on the canvas, you’ve used solid colors. And while there’s certainly nothing wrong with that, ambitious painters will be happy to hear that the canvas has a few fancier drawing techniques. For read more..

  • Page - 302

    HTML5: THE MISSING MANUAL, SECOND EDITION 282 SHADOWS AND FANCY FILLS TABLE 9-1 Properties for creating shadows PROPERTY DESCRIPTION shadowColor Sets the shadow’s color. You could go with black or a tinted color, but a nice midrange gray is generally best. Another good technique is to use a semitransparent color (page 185) so the content that’s underneath still shows read more..

  • Page - 303

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 283 SHADOWS AND FANCY FILLS context.fillStyle = "steelblue"; context.fillText("This is a subtle, slightly old-fashioned shadow.", 10, 175); context.shadowBlur = 5; context.shadowOffsetX = 20; context.shadowOffsetY = 20; context.fillStyle = "green"; context.fillText("This is a distant shadow...", 10, 225); read more..

  • Page - 304

    HTML5: THE MISSING MANUAL, SECOND EDITION 284 SHADOWS AND FANCY FILLS FIGURE 9-4 Left: An image that holds a single tile. Right: The pattern created by tiling the image over an entire canvas. Filling Shapes with Gradients The second type of fancy fill is a gradient, which blends two or more colors. The can- vas supports linear gradients and radial read more..

  • Page - 305

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 285 SHADOWS AND FANCY FILLS  TIP  If you’re looking at these gradients in a black-and-white print copy of this book, give your head a shake and try out the examples at http://prosetech.com/html5, so you can see the wild colors for yourself. (The sample code also includes the drawing logic for the hearts, read more..

  • Page - 306

    HTML5: THE MISSING MANUAL, SECOND EDITION 286 SHADOWS AND FANCY FILLS FIGURE 9-6 Left: Here’s the gradient generated for the bottom- left heart from Figure 9-5. When you use that gradi- ent to fill a shape, you see just a portion of it. Right: The same is true for this radial gradient, which is used for the bottom- right heart in Figure 9-5. In this read more..

  • Page - 307

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 287 SHADOWS AND FANCY FILLS To actually set the colors in a gradient, you call the gradient’s addColorStop() method. Each time you do, you supply an offset from 0 to 1, which sets where the color appears in the blend. A value of 0 means the color appears at the very start of the gradient, read more..

  • Page - 308

    HTML5: THE MISSING MANUAL, SECOND EDITION 288 SHADOWS AND FANCY FILLS  NOTE  Most often, you’ll choose the same center point for both the inner and outer circles. However, you could offset one from the other, which can stretch, squash, and distort the blend of colors in interesting ways. Using this example, you can create the final, multicolored radial read more..

  • Page - 309

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 289 SHADOWS AND FANCY FILLS FIGURE 9-7 Click your way through the ques- tions (top), and then review the scores (bottom). Unfortunately, without a scale or any kind of visual aid, it’s difficult for ordi- nary people to tell what these numbers are supposed to mean. read more..

  • Page - 310

    HTML5: THE MISSING MANUAL, SECOND EDITION 290 SHADOWS AND FANCY FILLS UP TO SPEED How to Convert One Personality into Five Numbers This five-factor personality test ranks you according to five personality “ingredients,” which are usually called open- ness, conscientiousness, extraversion, agreeableness, and neuroticism. These factors were cooked up when read more..

  • Page - 311

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 291 SHADOWS AND FANCY FILLS <div class="score"> <h2 id="headingO">Openness: </h2> <canvas id="canvasO" height="75" width="550"></canvas> </div> FIGURE 9-8 This page combines several different types of canvas drawing, including lines, images, and text. But the most read more..

  • Page - 312

    HTML5: THE MISSING MANUAL, SECOND EDITION 292 SHADOWS AND FANCY FILLS window.onload = function() { ... // Get the <canvas> element for the extraversion score. var canvasE = document.getElementById("canvasE"); // Add the score number to the corresponding heading. // (The score is stored in a variable named extraversion.) read more..

  • Page - 313

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 293 MAKING YOUR SHAPES INTERACTIVE The most important bit is the final line, which plots the star at the right position using this slightly messy equation: context.drawImage(img, (score+20)/40*440+35-17, 0); Here’s how it works. The first step is to convert the score into a percentage from 0 to 100 read more..

  • Page - 314

    HTML5: THE MISSING MANUAL, SECOND EDITION 294 MAKING YOUR SHAPES INTERACTIVE For example, if you draw a red square in the middle of your canvas, the moment you call stroke() or fill(), that square becomes nothing more than a block of red pixels. It may look like a square, but the canvas has no memory of its squareness. This model makes drawing fast. read more..

  • Page - 315

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 295 MAKING YOUR SHAPES INTERACTIVE FIGURE 9-9 This circle-drawing program is interactive. You can click to select a circle (at which point it becomes highlighted with a different border color) and drag it to a new position. Here’s a function that defines a circle with three details: the x- and read more..

  • Page - 316

    HTML5: THE MISSING MANUAL, SECOND EDITION 296 MAKING YOUR SHAPES INTERACTIVE If you want to get a bit fancier, you can pass arguments to the Circle() function. That way, you can create a circle object and set all the circle properties in one step. Here’s the version of the Circle() function that’s used for the page in Figure 9-9: function read more..

  • Page - 317

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 297 MAKING YOUR SHAPES INTERACTIVE // Redraw the canvas. drawCircles(); } This code makes use of a custom function named randomFromTo(), which generates random numbers in a set range. (To play with the full code, visit http://prosetech.com/html5.) The final step in this sequence is actually painting read more..

  • Page - 318

    HTML5: THE MISSING MANUAL, SECOND EDITION 298 MAKING YOUR SHAPES INTERACTIVE  NOTE  Each time the circle-drawing program refreshes the display, it starts by clearing everything away with the clearRect() method. Paranoid programmers might worry that this step would cause a flicker, as the canvas goes blank and the circles disappear, then reappear. However, the canvas read more..

  • Page - 319

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 299 MAKING YOUR SHAPES INTERACTIVE To determine if a click has landed in a shape, you need to use some math. In the case of a circle, you need to calculate the straight-line distance from the clicked point to the center of the circle. If the distance is less than or equal to the read more..

  • Page - 320

    HTML5: THE MISSING MANUAL, SECOND EDITION 300 ANIMATING THE CANVAS To finish this example, the drawing code in the drawCircles() function needs a slight tweak. Now it needs to single out the selected circle for special treatment (in this case, a thick, bold border): function drawCircles() { ... // Go through all the circles. for(var i=0; read more..

  • Page - 321

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 301 ANIMATING THE CANVAS someone hovers over it). You can also use animation to draw attention to changes in content (for example, fading in a new scene or creating graphs and charts that “grow” into the right positions). Used in these ways, animation is a powerful way to give your read more..

  • Page - 322

    HTML5: THE MISSING MANUAL, SECOND EDITION 302 ANIMATING THE CANVAS This call to setTimeout() is the heart of any animation task. For example, imagine you want to make a square fall from the top of the page to the bottom. To do this, you need to keep track of the square’s position using two global variables: // Set the square's initial read more..

  • Page - 323

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 303 ANIMATING THE CANVAS FIGURE 9-10 This test page lets you add as many balls as you want. You can choose the size of each ball (the de- fault is a 15-pixel radius), and you can switch on connecting lines (shown on right). Once added, each ball begins its own independent journey, falling down and read more..

  • Page - 324

    HTML5: THE MISSING MANUAL, SECOND EDITION 304 ANIMATING THE CANVAS // These are the details that represent an individual ball. function Ball(x, y, dx, dy, radius) { this.x = x; this.y = y; this.dx = dx; this.dy = dy; this.radius = radius; this.color = "red"; } // This is an array that will hold all the balls on the canvas. var read more..

  • Page - 325

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 305 ANIMATING THE CANVAS // Redraw every 20 milliseconds. setTimeout(drawFrame, 20); }; The drawFrame() function is the heart of this example. It not only paints the balls on the canvas, but it also calculates their current position and speed. The drawFrame() function uses a number of read more..

  • Page - 326

    HTML5: THE MISSING MANUAL, SECOND EDITION 306 ANIMATING THE CANVAS // Draw the ball. context.arc(ball.x, ball.y, ball.radius, 0, Math.PI*2); context.lineWidth = 1; context.fill(); context.stroke(); } // Draw the next frame in 20 milliseconds. setTimeout(drawFrame, 20); }  TIP  If you’re fuzzy about how the if statements read more..

  • Page - 327

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 307 A PRACTICAL EXAMPLE: THE MAZE GAME FREQUENTLY ASKED QUESTION Canvas Animations for Busy (or Lazy) People Do I really need to calculate everything on my own? For real? The most significant drawback to canvas animation is the fact that you need to do everything yourself. For example, if you want read more..

  • Page - 328

    HTML5: THE MISSING MANUAL, SECOND EDITION 308 A PRACTICAL EXAMPLE: THE MAZE GAME FIGURE 9-11 Guide the face through the maze. To a user, it looks like a fun game. To a de- veloper, it’s a potent mix of the HTML5 canvas and some smart JavaScript. Of course, there’s a trade-off. If you’re going to rely on the canvas to build some- thing read more..

  • Page - 329

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 309 A PRACTICAL EXAMPLE: THE MAZE GAME Setting Up the Maze Before anything can happen, the page needs to set up the canvas. Although you could paint the entire maze out of lines and rectangles, you’d need a lot of drawing code. Writing that drawing code by hand would be extremely tedious. You’d read more..

  • Page - 330

    HTML5: THE MISSING MANUAL, SECOND EDITION 310 A PRACTICAL EXAMPLE: THE MAZE GAME function drawMaze(mazeFile, startingX, startingY) { // Load the maze picture. imgMaze = new Image(); imgMaze.onload = function() { // Resize the canvas to match the size of the maze picture. canvas.width = imgMaze.width; canvas.height = imgMaze.height; read more..

  • Page - 331

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 311 A PRACTICAL EXAMPLE: THE MAZE GAME Animating the Face When the user hits a key, the face begins moving. For example, if the user presses the down key, the happy face continues moving down until it hits a barrier or another key is pressed. To make this work, the code uses two global read more..

  • Page - 332

    HTML5: THE MISSING MANUAL, SECOND EDITION 312 A PRACTICAL EXAMPLE: THE MAZE GAME The processKey() function doesn’t change the current position of the happy face, or attempt to draw it. Instead, this task happens every 10 milliseconds, when the drawFrame() function is called. The drawFrame() code is fairly straightforward, but detailed. It read more..

  • Page - 333

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 313 A PRACTICAL EXAMPLE: THE MAZE GAME // Draw a new frame in 10 milliseconds. setTimeout(drawFrame, 10); } You’ve now seen all the code for the maze game, except the innovative bit of logic in the checkForCollision() function, which handles the hit testing. That’s the topic you’ll tackle next. read more..

  • Page - 334

    HTML5: THE MISSING MANUAL, SECOND EDITION 314 A PRACTICAL EXAMPLE: THE MAZE GAME // Loop over each pixel and invert the color. for (var i = 0, n = pixels.length; i < n; i += 4) { // Get the data for one pixel. var red = pixels[i]; var green = pixels[i+1]; var blue = pixels[i+2]; var alpha = pixels[i+3]; // Invert the colors. read more..

  • Page - 335

    CHAPTER 9: ADVANCED CANVAS: INTERACTIVITY AND ANIMATION 315 A PRACTICAL EXAMPLE: THE MAZE GAME var alpha = pixels[i+3]; // Look for black walls (which indicates a collision). if (red == 0 && green == 0 && blue == 0) { return true; } // Look for gray edge space (which indicates a collision). if read more..

  • Page - 336

    read more..

  • Page - 337

    Building Web Apps PART 3 CHAPTER 10: Storing Your Data CHAPTER 11: Running Offline CHAPTER 12: Communicating with the Web Server CHAPTER 13: Geolocation, Web Workers, and History Management read more..

  • Page - 338

    read more..

  • Page - 339

    319 CHAPTER 10 On the Web, there are two places to store information: on the web server, or on the web client (the viewer’s computer). Certain types of data belong on one, while others work better on the other. The web server is the place to store sensitive information and data you don’t want people tampering with. For example, if read more..

  • Page - 340

    HTML5: THE MISSING MANUAL, SECOND EDITION 320 WEB STORAGE BASICS HTML5 introduces a better alternative that lets you store information on your visitor’s computer simply and easily. This data stays on the client indefinitely, isn’t sent to the web server (unless you do it yourself), has plenty of room, and works through a couple of simple, read more..

  • Page - 341

    CHAPTER 10: STORING YOUR DATA 321 WEB STORAGE BASICS  TIP  From the point of view of your web page code, both local storage and session storage work exactly the same. The difference is just how long the data lasts. Using local storage is the best bet for information you want to keep for future visits. Use session storage for data that you want to pass read more..

  • Page - 342

    HTML5: THE MISSING MANUAL, SECOND EDITION 322 WEB STORAGE BASICS Pulling something out of local storage is as easy as putting it in, provided you use the localStorage.getItem() method. For example, here’s a line of code that grabs the previously stored name and shows it in a message box: alert("You stored: " + localStorage.getItem("user_name")); This read more..

  • Page - 343

    CHAPTER 10: STORING YOUR DATA 323 WEB STORAGE BASICS  NOTE  Web storage also supports two alternate syntaxes for accessing data. Instead of using the getItem() and setItem() methods that you’ve already seen, you can use property names or an indexer. With property names, you access a storage slot called "user_name" as localStorage.user_name. With an indexer, read more..

  • Page - 344

    HTML5: THE MISSING MANUAL, SECOND EDITION 324 WEB STORAGE BASICS FIGURE 10-2 When a visitor leaves this page, either by navigating to a new site or by closing the window, the page offers to store the current position. Here’s the code that offers to store the position details: window.onbeforeunload = function(e) { // Check if the localStorage object read more..

  • Page - 345

    CHAPTER 10: STORING YOUR DATA 325 WEB STORAGE BASICS  TIP  Long key names, like mazeGame_currentX, are good. After all, it’s up to you to ensure that key names are unique, so two web pages on your website don’t inadvertently use the same name to store different pieces of data. With just a single container that holds all your data, it’s all too easy read more..

  • Page - 346

    HTML5: THE MISSING MANUAL, SECOND EDITION 326 DEEPER INTO WEB STORAGE Deeper into Web Storage You now know the essentials of web storage—how to put information in, and how to get it out again. However, there are several finer points and a few useful techniques left to cover before you put it to use. In the following sections, you’ll see how read more..

  • Page - 347

    CHAPTER 10: STORING YOUR DATA 327 DEEPER INTO WEB STORAGE When you click the button in this example, it triggers the findAllItems() function, which scans through the collection of items in local storage. Here’s the code: function findAllItems() { // Get the <ul> element for the list of items. var itemList = document.getElementById("itemList"); read more..

  • Page - 348

    HTML5: THE MISSING MANUAL, SECOND EDITION 328 DEEPER INTO WEB STORAGE The issue here is that JavaScript assumes you’re trying to stick two pieces of text together, rather than perform a mathematical operation. To solve the problem, you need to give JavaScript a hint that you’re trying to work with numbers. Several solutions are possible, but the read more..

  • Page - 349

    CHAPTER 10: STORING YOUR DATA 329 DEEPER INTO WEB STORAGE Storing Objects In the previous section, you saw how to convert numbers and dates to text and back again, so you can store them with web storage. These examples work because the JavaScript language helps you out, first with the handy Number() function, and then with the text-to-date read more..

  • Page - 350

    HTML5: THE MISSING MANUAL, SECOND EDITION 330 DEEPER INTO WEB STORAGE // Store it, in handy JSON format. sessionStorage.setItem("personalityScore", JSON.stringify(score)); // Go to the results page. window.location = "PersonalityTest_Score.html"; On the new page, you can pull the JSON text out of storage and use the JSON.parse() method to convert it back to read more..

  • Page - 351

    CHAPTER 10: STORING YOUR DATA 331 DEEPER INTO WEB STORAGE // Put the item in local storage. // (If the key already exists, the new item replaces the old.) localStorage.setItem(key, item); } The second page is just as simple. When the page first loads, it attaches a function to the window.onStorage event, using this code: window.onload = read more..

  • Page - 352

    HTML5: THE MISSING MANUAL, SECOND EDITION 332 READING FILES FIGURE 10-4 To see the onStorage event in action, open Storage Events1.html and StorageEvents2.html at the same time. When you add or change a value in the first page (top), the second page captures the event and reports it in the page (bottom). Reading Files Web storage is a solidly supported part of read more..

  • Page - 353

    CHAPTER 10: STORING YOUR DATA 333 READING FILES on the web page. This code can then open the file and explore its data, whether it’s simple text or something more complicated. The key thing is that the file goes directly to the JavaScript code. Unlike a normal file upload, it never needs to travel to the web server. It’s also important read more..

  • Page - 354

    HTML5: THE MISSING MANUAL, SECOND EDITION 334 READING FILES FIGURE 10-5 Click the Browse button (or Choose File, as it’s named in Chrome), choose a file, and then click OK. Instead of the usual upload, the web page JavaScript takes it from there, copying the content into your page. To build this example, you start with the <input type="file"> read more..

  • Page - 355

    CHAPTER 10: STORING YOUR DATA 335 READING FILES It’s almost time to call one of the FileReader’s methods to extract the file content. All of these methods are asynchronous, which means they start the file-reading task but don’t wait for the data. To get the data, you first need to handle the onLoad event: reader.onload = function (e) { // read more..

  • Page - 356

    HTML5: THE MISSING MANUAL, SECOND EDITION 336 READING FILES  NOTE  Blob is shorthand for binary large object—in other words, a fat chunk of raw data. Blobs are an advanced part of the File API; to learn more, you can take a look at Mozilla’s steadily evolving documentation on the subject at http://tinyurl.com/file-blob. Lastly, the readAsDataURL() method gives you read more..

  • Page - 357

    CHAPTER 10: STORING YOUR DATA 337 READING FILES for (var i=0; i<files.length; i++) { // Get the next file var file = files[i]; // Create a FileReader for this file, and run the usual code here. var reader = new FileReader(); reader.onload = function (e) { ... }; reader.readAsText(file); } Reading an Image File with Drag-and-Drop As read more..

  • Page - 358

    HTML5: THE MISSING MANUAL, SECOND EDITION 338 READING FILES Some straightforward style sheet magic gives the drop box the size, borders, and colors you want: #dropBox { margin: 15px; width: 300px; height: 300px; border: 5px dashed gray; border-radius: 8px; background: lightyellow; background-size: 100%; background-repeat: no-repeat; text-align: read more..

  • Page - 359

    CHAPTER 10: STORING YOUR DATA 339 READING FILES e.stopPropagation(); e.preventDefault(); } The onDrop event is more important. It’s at this point that you get the file and process it. However, because there are actually two ways to submit files to this page, the drop() function calls the processFiles() function to do the actual work: function read more..

  • Page - 360

    HTML5: THE MISSING MANUAL, SECOND EDITION 340 INDEXEDDB: A DATABASE ENGINE IN A BROWSER The FileReader provides several more events, and when reading image files you might choose to use them. The onProgress event fires periodically during long op- erations, to let you know how much data has been loaded so far. (You can cancel an read more..

  • Page - 361

    CHAPTER 10: STORING YOUR DATA 341 INDEXEDDB: A DATABASE ENGINE IN A BROWSER UP TO SPEED The Difference Between Server-Side and Client-Side Databases There are plenty of ways for websites to use server-side data- bases, but none of them have anything to do with HTML5. To understand why, you need to remember that the HTML5 uni- verse is read more..

  • Page - 362

    HTML5: THE MISSING MANUAL, SECOND EDITION 342 INDEXEDDB: A DATABASE ENGINE IN A BROWSER  NOTE  The IndexedDB storage system behaves like local storage in several key ways. Most importantly, an IndexedDB database belongs to a single person, using a particular browser and a particular computer, and visiting a specific site. If you change any of these details—for read more..

  • Page - 363

    CHAPTER 10: STORING YOUR DATA 343 INDEXEDDB: A DATABASE ENGINE IN A BROWSER FIGURE 10-7 This example uses an IndexedDB database to hold link information. The top of the page has a form that lets you create a new link record. Underneath is a list that shows the name and URL (but not the other details) of every link that’s in the database. As read more..

  • Page - 364

    HTML5: THE MISSING MANUAL, SECOND EDITION 344 INDEXEDDB: A DATABASE ENGINE IN A BROWSER So, what does your code need to do when the page loads? That depends on what you’ve done before: • If this is the first time the user is visiting the page, you need to create the da- tabase and set up its tables from scratch. read more..

  • Page - 365

    CHAPTER 10: STORING YOUR DATA 345 INDEXEDDB: A DATABASE ENGINE IN A BROWSER The onError event is equally straightforward. Depending on the error, you may be able to take corrective action, or you may simply choose to report it to the user with a message either in a pop-up box or right on the page. request.onerror = function(event) read more..

  • Page - 366

    HTML5: THE MISSING MANUAL, SECOND EDITION 346 INDEXEDDB: A DATABASE ENGINE IN A BROWSER UP TO SPEED Understanding Primary Keys The primary key is the bit of information that uniquely identifies each record. In the case of the Links table, each link record has a unique URL, so it makes sense to use that for the key. This setup read more..

  • Page - 367

    CHAPTER 10: STORING YOUR DATA 347 INDEXEDDB: A DATABASE ENGINE IN A BROWSER Transactions are important in the IndexedDB world because there are so many ways that a database operation can be interrupted. For example, if the user closes the browser while the page is still at work, the browser interrupts your code mid-task. The transaction system read more..

  • Page - 368

    HTML5: THE MISSING MANUAL, SECOND EDITION 348 INDEXEDDB: A DATABASE ENGINE IN A BROWSER // Create the LinkRecord object. var linkRecord = new LinkRecord(name, url, description, notes); Now you’re ready to follow step 1 from the list and create your transaction. To do that, you call the database.transaction() method and provide two parameters: read more..

  • Page - 369

    CHAPTER 10: STORING YOUR DATA 349 INDEXEDDB: A DATABASE ENGINE IN A BROWSER Querying All the Records in a Table Querying is the essential job of retrieving your stored information. You pick out a single record, search for a group of records that match certain criteria, or travel through all the records in your table, whichever you prefer. The link tracker read more..

  • Page - 370

    HTML5: THE MISSING MANUAL, SECOND EDITION 350 INDEXEDDB: A DATABASE ENGINE IN A BROWSER Your data is returned to you as an object. In the link tracker example, each record is a genuine LinkRecord object, complete with the name, url, description, and notes properties outlined in the object-definition function on page 342. Once you retrieve read more..

  • Page - 371

    CHAPTER 10: STORING YOUR DATA 351 INDEXEDDB: A DATABASE ENGINE IN A BROWSER When you reach the last record in the table, the cursor will evaluate to false. At this point, it’s time to copy your markup into the page: else { // If there wasn't at least one result, substitute some placeholder text. if read more..

  • Page - 372

    HTML5: THE MISSING MANUAL, SECOND EDITION 352 INDEXEDDB: A DATABASE ENGINE IN A BROWSER var resultsElement = document.getElementById("linkDetails"); resultsElement.innerHTML = "<b>" + linkRecord.name + "</b><br>" + "<b>URL:</b> " + linkRecord.url + "<br>" + "<b>Description:</b> " read more..

  • Page - 373

    CHAPTER 10: STORING YOUR DATA 353 INDEXEDDB: A DATABASE ENGINE IN A BROWSER function deleteLink(element) { var url = element.getAttribute("data-url"); var transaction = database.transaction(["Links"], "readwrite"); var objectStore = transaction.objectStore("Links"); var request = objectStore.delete(url); request.onerror = function(event) { read more..

  • Page - 374

    read more..

  • Page - 375

    355 CHAPTER 11 If you want to view a website, you need to connect to the Internet. Everybody knows that. So why a chapter about offline applications? The very notion seems so last century. After all, didn’t web applications overthrow several generations of offline, desktop applications on their way to conquering the world? And there read more..

  • Page - 376

    HTML5: THE MISSING MANUAL, SECOND EDITION 356 CACHING FILES WITH A MANIFEST and tablets. The big advantage is that your HTML5-powered mini-app can run on any device, whereas a native app is locked into a specific platform. In this chapter, you’ll learn how to turn any web page (or group of web pages) into an offline application. You’ll read more..

  • Page - 377

    CHAPTER 11: RUNNING OFFLINE 357 CACHING FILES WITH A MANIFEST 2. Modify your web page so it refers to the manifest. That way, the browser knows to download the manifest file when someone requests the page. 3. Configure the web server. Most importantly, the web server needs to serve manifest files with the proper MIME type. But read more..

  • Page - 378

    HTML5: THE MISSING MANUAL, SECOND EDITION 358 CACHING FILES WITH A MANIFEST  NOTE  Watch for typos. If you attempt to cache a file that doesn’t exist, the browser will ignore not just that file, but the entire manifest. With an offline application, the browser must cache everything your application needs. That includes web pages and the resources these read more..

  • Page - 379

    CHAPTER 11: RUNNING OFFLINE 359 CACHING FILES WITH A MANIFEST to recognize the file extension. If you’re running your own web server, you can use the setup steps described on page 360. If not, you need to talk to your web host- ing company and ask them what file extensions they use to support manifest files. TROUBLESHOOTING MOMENT Don’t read more..

  • Page - 380

    HTML5: THE MISSING MANUAL, SECOND EDITION 360 CACHING FILES WITH A MANIFEST It should come as no surprise that you can’t test offline applications when you’re launching files from your hard drive. Instead, you need to put your application on a web server (or use a test web server that runs on your computer, like read more..

  • Page - 381

    CHAPTER 11: RUNNING OFFLINE 361 CACHING FILES WITH A MANIFEST FIGURE 11-1 Firefox shows this message when it loads a web page that uses a manifest. Click Allow to grant permission to download and cache all the files that are listed in the manifest. On subsequent visits, when Firefox detects a changed manifest, it will download the new files without read more..

  • Page - 382

    HTML5: THE MISSING MANUAL, SECOND EDITION 362 CACHING FILES WITH A MANIFEST 5. Browse to one of the pages in your offline application, and refresh it. Ordinarily, when you click the Refresh or Reload button, your browser always tries to make contact with the web server. If you’re requesting an ordinary page and you’ve lost your Internet read more..

  • Page - 383

    CHAPTER 11: RUNNING OFFLINE 363 CACHING FILES WITH A MANIFEST Not necessarily. To trigger an update for a cached web application, you need to meet three criteria: • The manifest file can’t be cached in the browser. If the browser has a locally cached copy of the manifest file, it won’t bother to check the web server at all. read more..

  • Page - 384

    HTML5: THE MISSING MANUAL, SECOND EDITION 364 CACHING FILES WITH A MANIFEST The next time you need browsers to update their caches, simply change the version number in this example to 1.00.002, and so on. Presto—you now have a way to force updates and keep track of how many updates you’ve uploaded. Updates aren’t instantaneous. When the read more..

  • Page - 385

    CHAPTER 11: RUNNING OFFLINE 365 CACHING FILES WITH A MANIFEST FIGURE 11-3 Top: In the Firefox menu, click Options, choose the Advanced icon, and then choose the Network tab to end up here. You can review the space usage of every website, or clear the cached resources of any one, by selecting it and clicking Remove. In this example, there’s just one read more..

  • Page - 386

    HTML5: THE MISSING MANUAL, SECOND EDITION 366 PRACTICAL CACHING TECHNIQUES FREQUENTLY ASKED QUESTION How Much Can You Cache? Are there limits on how much information can be cached? Different browsers impose wildly different size restrictions on offline applications. Mobile browsers are the most obvious example. Because they run on space-limited read more..

  • Page - 387

    CHAPTER 11: RUNNING OFFLINE 367 PRACTICAL CACHING TECHNIQUES However, the manifest caches just one of the pictures: CACHE MANIFEST PersonalityTest.html PersonalityTest_Score.html PersonalityTest.css PersonalityTest.js Images/emotional_bear.jpg You might assume that a browser will grab the emotional_bear.png picture from its cache, while requesting logo.png from the web server read more..

  • Page - 388

    HTML5: THE MISSING MANUAL, SECOND EDITION 368 PRACTICAL CACHING TECHNIQUES You can also use the asterisk to target files of a specific type (for example, *.jpg refers to all JPEG images) or all the files on a specific server (for example, http:// www.google-analytics.com/* refers to all the resources on the Google Analytics web domain).  NOTE  read more..

  • Page - 389

    CHAPTER 11: RUNNING OFFLINE 369 PRACTICAL CACHING TECHNIQUES FALLBACK: PersonalityScore.html PersonalityScore_offline.html Images/emotional_bear.jpg Images/emotional_bear_small.jpg PersonalityTest.js PersonalityTest_offline.js NETWORK: *  NOTE  Incidentally, the files that you want to cache are part of the CACHE: section in the manifest. You can add the section title if you want, but you read more..

  • Page - 390

    HTML5: THE MISSING MANUAL, SECOND EDITION 370 PRACTICAL CACHING TECHNIQUES Incidentally, you can write more targeted fallbacks that still use the slash to match all the files in a specific subfolder, like this: FALLBACK: /paint_app/ offline.html GEM IN THE ROUGH How to Bypass the Cache When You’re Online When you load up a cached page, the browser expects to read more..

  • Page - 391

    CHAPTER 11: RUNNING OFFLINE 371 PRACTICAL CACHING TECHNIQUES The original version of the web page refers to the online.js JavaScript file: <!DOCTYPE html> <html lang="en" manifest="personality.manifest"> <head> <meta charset="utf-8"> <title>...</title> <script src="online.js"></script> ... It contains this read more..

  • Page - 392

    HTML5: THE MISSING MANUAL, SECOND EDITION 372 PRACTICAL CACHING TECHNIQUES TABLE 11-1 Caching events EVENT DESCRIPTION onChecking When the browser spots the manifest attribute in a web page, it fires this event and checks the web server for the corresponding manifest file. onNoUpdate If the browser has already downloaded the manifest, and the manifest hasn’t changed, it fires this read more..

  • Page - 393

    CHAPTER 11: RUNNING OFFLINE 373 PRACTICAL CACHING TECHNIQUES FIGURE 11-5 If you’re a micromanager at heart, you can take control of the caching process. But first you need to understand how the caching event unfolds, as depicted in this diagram. The process stops when the browser reaches one of the square boxes (with a bold border) shown here. Or, you can read more..

  • Page - 394

    HTML5: THE MISSING MANUAL, SECOND EDITION 374 PRACTICAL CACHING TECHNIQUES if (confirm( "A new version of this application is available. Reload now?")) { window.location.reload(); } } } </script> Figure 11-6 shows this code at work. FIGURE 11-6 Here, the application offers to reload itself with the newly downloaded content, if read more..

  • Page - 395

    375 CHAPTER 12 When you started your journey with HTML5, you began with its markup- based features, like semantic elements, web forms, and video. But as you progressed through this book, you slowly shifted your focus to web page programming and the JavaScript-powered parts of HTML5. Now you’re about to dip your toe into a few HTML5 read more..

  • Page - 396

    HTML5: THE MISSING MANUAL, SECOND EDITION 376 SENDING MESSAGES TO THE WEB SERVER forth conversation. But before you explore either of these, you’ll start with a review of the current-day tool for web server communication: the XMLHttpRequest object.  NOTE  Server-sent events and web sockets seem deceptively simple. It’s easy enough to learn how they work and read more..

  • Page - 397

    CHAPTER 12: COMMUNICATING WITH THE WEB SERVER 377 SENDING MESSAGES TO THE WEB SERVER The XMLHttpRequest Object The chief tool that lets a web page speak to a web server is the XMLHttpRequest object. The XMLHttpRequest object was originally created by Microsoft to improve the web version of its Outlook email program, but it steadily spread to every read more..

  • Page - 398

    HTML5: THE MISSING MANUAL, SECOND EDITION 378 SENDING MESSAGES TO THE WEB SERVER FIGURE 12-1 Click the “Ask the Server” button, and this web page creates an XMLHttpRequest object and sends the two numbers to the web server. The web server runs a simple script to calculate the answer and then returns the result (shown later, in Figure 12-2). CREATING read more..

  • Page - 399

    CHAPTER 12: COMMUNICATING WITH THE WEB SERVER 379 SENDING MESSAGES TO THE WEB SERVER For example, if you place the PHP script in a file named WebCalculator.php, a web request might look like this: http://www.magicXMLHttpRequest.com/WebCalculator.php?number1=34&number2=46 Here, the URL holds two pieces of information tacked onto the end, in the URL sec- tion known as read more..

  • Page - 400

    HTML5: THE MISSING MANUAL, SECOND EDITION 380 SENDING MESSAGES TO THE WEB SERVER CALLING THE WEB SERVER The second step is to build the page that uses the PHP script, with the help of XML- HttpRequest. It all starts out simply enough. At the beginning of the script code, an XMLHttpRequest object is created, so it will be available in all read more..

  • Page - 401

    CHAPTER 12: COMMUNICATING WITH THE WEB SERVER 381 SENDING MESSAGES TO THE WEB SERVER response when its work is done. Here, the code links the event to another function in the page, named handleServerResponse(): req.onreadystatechange = handleServerResponse; Now you can start the process with the XMLHttpRequest object’s send() method. Just remember, your read more..

  • Page - 402

    HTML5: THE MISSING MANUAL, SECOND EDITION 382 SENDING MESSAGES TO THE WEB SERVER FIGURE 12-2 The web server has returned a response, trig- gering a JavaScript function, which changed the page. Getting New Content Another scenario where XMLHttpRequest comes in handy is loading new HTML con- tent into a page. For example, a news article might contain multiple read more..

  • Page - 403

    CHAPTER 12: COMMUNICATING WITH THE WEB SERVER 383 SENDING MESSAGES TO THE WEB SERVER FIGURE 12-3 This page splits its content into separate slides. Click the Previous or Next link to load in a new slide, with different text content and a new picture. To make this work, the page uses the XMLHttpRequest object to request the new content as it’s read more..

  • Page - 404

    HTML5: THE MISSING MANUAL, SECOND EDITION 384 SENDING MESSAGES TO THE WEB SERVER To build the example in Figure 12-3, you first need to carve out a spot for the dy- namic content. Here it’s a <div> element that creates a golden box and has two links underneath: <div id="slide">Click Next to start the show.</div> <a onclick="return read more..

  • Page - 405

    CHAPTER 12: COMMUNICATING WITH THE WEB SERVER 385 SENDING MESSAGES TO THE WEB SERVER a low-tech solution that works on any web server—it looks for a file with a specific name. For example, the file with the first slide is named ChinaSites1_slide.html, the file with the second is ChinaSites2_slide.html, and so on. Each file contains a scrap of HTML read more..

  • Page - 406

    HTML5: THE MISSING MANUAL, SECOND EDITION 386 SERVER-SENT EVENTS changes to match the currently displayed slide. But for now, it’s time to move on to two new ways to communicate with the web server.  NOTE  If you’re using the popular jQuery JavaScript toolkit, you probably won’t use XMLHttpRequest directly. Instead, you’ll use jQuery methods, like read more..

  • Page - 407

    CHAPTER 12: COMMUNICATING WITH THE WEB SERVER 387 SERVER-SENT EVENTS TABLE 12-1 Browser support for server-sent events IE FIREFOX CHROME SAFARI OPERA SAFARI IOS CHROME FOR ANDROID Minimum version - 6 6 5 11 4 29 In the following sections, you’ll put together a simple example that demonstrates server-sent events. The Message Format Unlike XMLHttpRequest, the server-sent events read more..

  • Page - 408

    HTML5: THE MISSING MANUAL, SECOND EDITION 388 SERVER-SENT EVENTS Your web page pays attention to the message data, but it doesn’t deal with the ID and connection timeout information. Instead, the browser uses these details. For example, after reading the above message, the browser knows that if it loses it con- nection to the web server, it should read more..

  • Page - 409

    CHAPTER 12: COMMUNICATING WITH THE WEB SERVER 389 SERVER-SENT EVENTS The server-side part of this example simply reports the time, in regular intervals. Here’s the complete script, at a glance: <?php header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); ob_end_clean(); // Start a loop that goes forever. do { // Get the read more..

  • Page - 410

    HTML5: THE MISSING MANUAL, SECOND EDITION 390 SERVER-SENT EVENTS (for PHP end of line), which is a shorthand way of referring to the \n character se- quence described earlier: echo 'data: ' . $currentTime . PHP_EOL; echo PHP_EOL;  NOTE  If this looks funny, it’s probably because PHP uses the dot operator (.) to join strings. It works in the same read more..

  • Page - 411

    CHAPTER 12: COMMUNICATING WITH THE WEB SERVER 391 SERVER-SENT EVENTS var source; function startListening() { source = new EventSource("TimeEvents.php"); source.onmessage = receiveMessage; messageLog.innerHTML += "<br>" + "Started listening for messages."; }  TIP  To check for server-side event support, you can test if the window.EventSource property read more..

  • Page - 412

    HTML5: THE MISSING MANUAL, SECOND EDITION 392 SERVER-SENT EVENTS only difference is that the web server tells the browser how often it should check for new information. In a page that uses traditional polling, this detail is built into your JavaScript code. The following script uses a hybrid approach. It stays connected (and sends periodic messages) for read more..

  • Page - 413

    CHAPTER 12: COMMUNICATING WITH THE WEB SERVER 393 WEB SOCKETS  NOTE  With complex server scripts, the web browser’s automatic reconnection feature may not work out so well. For example, the connection may have been cut off while the web server was in the middle of a specific task. In this case, your web server code can send each client an ID (as described on read more..

  • Page - 414

    HTML5: THE MISSING MANUAL, SECOND EDITION 394 WEB SOCKETS back and forth very quickly (like you might in a chat application, for example). Second, there’s no way to associate one call with the next, so every time the web page makes a request, the web server needs to sort out who you are all over again. If your web page needs to make a read more..

  • Page - 415

    CHAPTER 12: COMMUNICATING WITH THE WEB SERVER 395 WEB SOCKETS  NOTE  Many web hosts won’t allow long-running programs, unless you pay for a dedicated server (a web server that’s allocated to your website, and no one else’s). If you’re using ordinary shared hosting, you probably can’t create web pages that use the web socket feature. Even if you can read more..

  • Page - 416

    HTML5: THE MISSING MANUAL, SECOND EDITION 396 WEB SOCKETS Simply creating a new WebSocket object causes your page to attempt to connect to the server. You deal with what happens next using one of the WebSocket’s four events: onOpen (when the connection is first established), onError (when there’s a problem), onClose (when the connection is read more..

  • Page - 417

    CHAPTER 12: COMMUNICATING WITH THE WEB SERVER 397 WEB SOCKETS  NOTE  A lot of behind-the-scenes work takes place to make a web socket connection work. First, the web page makes contact using the well-worn HTTP standard. Then it needs to “upgrade” its connection to a web socket connection that allows unfettered back-and-forth communication. At this point, you could read more..

  • Page - 418

    HTML5: THE MISSING MANUAL, SECOND EDITION 398 WEB SOCKETS FIGURE 12-6 A web socket server that simply repeats what you say won’t win any prizes in software innovation. However, it does let you see how easy it is to talk to a ready-made web socket server. Incidentally, you can check the readyState property of your socket to determine whether it’s read more..

  • Page - 419

    CHAPTER 12: COMMUNICATING WITH THE WEB SERVER 399 WEB SOCKETS And it’s just as easy to take the messages you receive and insert them into the page: function messageReceived(e) { messageLog.innerHTML += "<br>" + "Message received: " + e.data; }  NOTE  If you want to look at a slightly more exciting example, check out the chat free-for-all at read more..

  • Page - 420

    read more..

  • Page - 421

    401 CHAPTER 13 By now, you know all about the key themes of HTML5. You’ve used it to write more meaningful and better-structured markup. You’ve seen its rich graphical features, like video and dynamic drawing. And you’ve used it to create self- sufficient, JavaScript-powered pages that can work even without a web connection. In this chapter, read more..

  • Page - 422

    HTML5: THE MISSING MANUAL, SECOND EDITION 402 GEOLOCATION wrinkles, like the challenge of keeping the browser URL synchronized with the current content. Web developers use plenty of advanced techniques to keep things in order, and now HTML5 adds a session history tool that can help.  NOTE  As you explore these last three features, you’ll get a read more..

  • Page - 423

    CHAPTER 13: GEOLOCATION, WEB WORKERS, AND HISTORY MANAGEMENT 403 GEOLOCATION FIGURE 13-1 Here a web page wants location data, and Firefox asks whether you want to allow it just this once (click Share Location), to allow it every time (Always Share), or never to allow it (Never Share). This behavior isn’t just Firefox being polite; the geolocation standard read more..

  • Page - 424

    HTML5: THE MISSING MANUAL, SECOND EDITION 404 GEOLOCATION If you’re using a web-enabled phone, the location provider provides a similar trian- gulation process, but it uses the signals from different cellphone towers. This quick, relatively effective procedure usually gets your position down to less than a kilometer. (More industrialized areas—like read more..

  • Page - 425

    CHAPTER 13: GEOLOCATION, WEB WORKERS, AND HISTORY MANAGEMENT 405 GEOLOCATION Finding a Visitor’s Coordinates The geolocation feature is strikingly simple. It consists of three methods that are packed into the navigator.geolocation object: getCurrentPosition(), watchPosi- tion(), and clearWatch().  NOTE  If you aren’t already familiar with the navigator object, it’s a read more..

  • Page - 426

    HTML5: THE MISSING MANUAL, SECOND EDITION 406 GEOLOCATION FIGURE 13-2 Top: First, you need to agree to let the browser tell the web server about your position. Bottom: The results are in—your coordinates on the globe. Remember, you need to use a browser that supports geolocation and let the web page track you. Also, it’s a good idea to upload your read more..

  • Page - 427

    CHAPTER 13: GEOLOCATION, WEB WORKERS, AND HISTORY MANAGEMENT 407 GEOLOCATION POWER USERS’ CLINIC Finding Out the Accuracy of a Geolocation Guess When the getCurrentPosition() method meets with success, your code gets a position object that has two proper- ties: timestamp (which records when the geolocation was performed) and coords (which indicates the read more..

  • Page - 428

    HTML5: THE MISSING MANUAL, SECOND EDITION 408 GEOLOCATION function geolocationSuccess(position) { results.innerHTML = "You were last spotted at (" + position.coords.latitude + "," + position.coords.longitude + ")"; } function geolocationFailure(positionError) { results.innerHTML = "Geolocation failed."; } When the error function is called, the browser hands read more..

  • Page - 429

    CHAPTER 13: GEOLOCATION, WEB WORKERS, AND HISTORY MANAGEMENT 409 GEOLOCATION navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationFailure, {enableHighAccuracy: true}); And here’s an example that sets all three: navigator.geolocation.getCurrentPosition( geolocationSuccess, geolocationFailure, {enableHighAccuracy: true, timeout: 10000, maximumAge: 60000} ); Both of these examples read more..

  • Page - 430

    HTML5: THE MISSING MANUAL, SECOND EDITION 410 GEOLOCATION map. For example, a Google Maps–fortified pa ge can show visitors your business locations or flag interesting sights in a Manhattan walking tour. To get started with Google Maps, check out the documentation at http://tinyurl.com/maps-docs.  NOTE  Google Maps is free to use, even for commercial websites, read more..

  • Page - 431

    CHAPTER 13: GEOLOCATION, WEB WORKERS, AND HISTORY MANAGEMENT 411 GEOLOCATION Next, you need a <div> element that will hold the dynamically generated map. Give it a unique ID for easy reference: <body> <p id="results">Where do you live?</p> <div id="mapSurface"></div> </body> You can then use a style sheet rule to read more..

  • Page - 432

    HTML5: THE MISSING MANUAL, SECOND EDITION 412 GEOLOCATION goToDefaultLocation(); } }; Even after you’ve created the map with this code, you still won’t see it in the page. That’s because you haven’t set a geographic position. To do that, you need to create a specific global point using the LatLng object. You can then place that point read more..

  • Page - 433

    CHAPTER 13: GEOLOCATION, WEB WORKERS, AND HISTORY MANAGEMENT 413 GEOLOCATION Monitoring a Visitor’s Moves All the examples you’ve used so far have relied on the getCurrentPosition() method, which is the heart of geolocation. However, the geolocation object has two more methods that allow you to track a visitor’s position, so your page receives notifica- read more..

  • Page - 434

    HTML5: THE MISSING MANUAL, SECOND EDITION 414 WEB WORKERS Web Workers Way back when JavaScript was first created, no one worried too much about per- formance. JavaScript was built to be a straightforward language for running small bits of script in a web page. JavaScript was a frill—a simplified scripting language for amateur programmers. It certainly read more..

  • Page - 435

    CHAPTER 13: GEOLOCATION, WEB WORKERS, AND HISTORY MANAGEMENT 415 WEB WORKERS UP TO SPEED Web Worker Safety Measures JavaScript’s web worker lets your code work in the background while something else takes place in the foreground. This brings up a well-known theme of modern programming: If an applica- tion can do two things at once, one read more..

  • Page - 436

    HTML5: THE MISSING MANUAL, SECOND EDITION 416 WEB WORKERS The markup is short and concise. The page uses two <input> controls, one for each text box. It also includes a button to start the search and two <div> elements, one to hold the results and another to hold the status message underneath. Here’s the complete markup from read more..

  • Page - 437

    CHAPTER 13: GEOLOCATION, WEB WORKERS, AND HISTORY MANAGEMENT 417 WEB WORKERS // Perform the prime search. (This is the time-consuming step.) var primes = findPrimes(fromNumber, toNumber); // Loop over the array of prime numbers, and paste them together into // one long piece of text. var primeList = ""; for (var i=0; i<primes.length; i++) { read more..

  • Page - 438

    HTML5: THE MISSING MANUAL, SECOND EDITION 418 WEB WORKERS Web pages and web workers communicate by exchanging messages. To send data to a worker, you call the worker’s postMessage() method: worker.postMessage(myData); The worker then receives an onMessage event that provides a copy of the data. This is when it starts working. Similarly, when your read more..

  • Page - 439

    CHAPTER 13: GEOLOCATION, WEB WORKERS, AND HISTORY MANAGEMENT 419 WEB WORKERS var worker; function doSearch() { // Disable the button, so the user can't start more than one search // at the same time. searchButton.disabled = true; // Create the worker. worker = new Worker("PrimeWorker.js"); // Hook up to the onMessage event, so you can read more..

  • Page - 440

    HTML5: THE MISSING MANUAL, SECOND EDITION 420 WEB WORKERS When the worker calls postMessage(), it fires the onMessage event, which triggers this function in the web page: function receivedWorkerMessage(event) { // Get the prime number list. var primes = event.data; // Copy the list to the page. ... // Allow more searches. searchButton.disabled = read more..

  • Page - 441

    CHAPTER 13: GEOLOCATION, WEB WORKERS, AND HISTORY MANAGEMENT 421 WEB WORKERS Handling Worker Errors As you’ve learned, the postMessage() method is the key to communicating with web workers. However, there’s one more way that a web worker can notify your web page—with the onerror event that signals an error: worker.onerror = workerError; Now, if some read more..

  • Page - 442

    HTML5: THE MISSING MANUAL, SECOND EDITION 422 WEB WORKERS FIGURE 13-6 As the prime number search is under way, the search updates the status display to tell you how close the task is to completion. For a fancier display, you could use a color-filling progress bar like the one on page 165. To build the progress display, the web worker needs to send read more..

  • Page - 443

    CHAPTER 13: GEOLOCATION, WEB WORKERS, AND HISTORY MANAGEMENT 423 WEB WORKERS Here’s how you would rewrite the web worker code to add a message type to the prime number list: onmessage = function(event) { // Perform the prime number search. var primes = findPrimes(event.data.from, event.data.to); // Send back the results. postMessage( read more..

  • Page - 444

    HTML5: THE MISSING MANUAL, SECOND EDITION 424 WEB WORKERS else if (message.messageType == "Progress") { // Report the current progress. statusDisplay.innerHTML = message.data + "% done ..."; } }  NOTE  There’s another way to design this page. You could get the worker to call postMessage() every time it finds a prime number. The web read more..

  • Page - 445

    CHAPTER 13: GEOLOCATION, WEB WORKERS, AND HISTORY MANAGEMENT 425 HISTORY MANAGEMENT TABLE 13-1 Browser support for web workers IE FIREFOX CHROME SAFARI OPERA SAFARI IOS CHROME FOR ANDROID Minimum version 10 3.5 3 4 10.6 5 29 So what can you do if you face a browser that doesn’t have web worker support? The easiest option is to simply do the same work in read more..

  • Page - 446

    HTML5: THE MISSING MANUAL, SECOND EDITION 426 HISTORY MANAGEMENT in the browser’s History list (the list of recently visited web pages that the browser maintains as you skip from page to page across the Web). Here’s an example that uses it: alert("You have " + history.length + " pages in your browser's history list."); The most useful read more..

  • Page - 447

    CHAPTER 13: GEOLOCATION, WEB WORKERS, AND HISTORY MANAGEMENT 427 HISTORY MANAGEMENT where it is. And this problem grows worse if there are more than just five slides—for example, a Flickr photo stream could have dozens or hundreds of pictures. FIGURE 13-7 Here are two versions of the ChinaSites.html page, with different slides loaded. In both pages, the read more..

  • Page - 448

    HTML5: THE MISSING MANUAL, SECOND EDITION 428 HISTORY MANAGEMENT fetch the corresponding bit of dynamic content from the web server. All of this adds up to a fair bit of juggling, but you can use a JavaScript library like PathJS ( https:// github.com/mtrpcic/pathjs) to make life much easier. Recently, the hashbang technique has fallen into disrepute, and many read more..

  • Page - 449

    CHAPTER 13: GEOLOCATION, WEB WORKERS, AND HISTORY MANAGEMENT 429 HISTORY MANAGEMENT So far, this sounds like a perfect solution. However, there’s a significant drawback. If you want this system to work the way it’s intended, you actually need to create a page for every URL you use. In this example, that means you need to create China- read more..

  • Page - 450

    HTML5: THE MISSING MANUAL, SECOND EDITION 430 HISTORY MANAGEMENT function previousSlide() { if (slideNumber == 1) { slideNumber = 5; } else { slideNumber -= 1; } history.pushState(slideNumber, null, "ChinaSites" + slideNumber + ".html"); goToNewSlide(); return false; } The goToNewSlide() function hasn’t changed from the read more..

  • Page - 451

    CHAPTER 13: GEOLOCATION, WEB WORKERS, AND HISTORY MANAGEMENT 431 HISTORY MANAGEMENT // What's the slide number for this state? // (You could also snip it out of the URL, using the location.href // property, but that's more work.) slideNumber = e.state; // Request this slide from the web server. goToNewSlide(); } }; read more..

  • Page - 452

    HTML5: THE MISSING MANUAL, SECOND EDITION 432 HISTORY MANAGEMENT Browser Compatibility for Session History Session history has roughly the same level of support as the web workers feature. Once again, it’s pre–IE 10 versions of Internet Explorer that are most likely to cause a problem (see Table 13-2). TABLE 13-2 Browser support for session read more..

  • Page - 453

    Appendixes PART 4 APPENDIX A: Essential CSS APPENDIX B: JavaScript: The Brains of Your Page read more..

  • Page - 454

    read more..

  • Page - 455

    435 APPENDIX A It’s no exaggeration to say that modern web design wouldn’t be possible without CSS, the Cascading Style Sheet standard. CSS allows even the most richly format- ted, graphically complex web pages to outsource the formatting work to a separate document—a style sheet. This keeps the web page markup clean, clear, and read more..

  • Page - 456

    HTML5: THE MISSING MANUAL, SECOND EDITION 436 THE ANATOMY OF A STYLE SHEET The second approach is to embed an entire style sheet in a <style> element, which you must place in the page’s <head> section: <head> <title>Embedded Style Sheet Test</title> <style> ... </style> </head> This code separates read more..

  • Page - 457

    APPENDIX A: ESSENTIAL CSS 437 THE ANATOMY OF A STYLE SHEET Each rule applies one or more formatting details to one or more HTML elements. Here’s the structure of a simple rule: selector { property: value; property: value; } And here’s what each part means: • The selector identifies the type of content you want to format. A browser read more..

  • Page - 458

    HTML5: THE MISSING MANUAL, SECOND EDITION 438 THE ANATOMY OF A STYLE SHEET TABLE A-1 Commonly used style sheet properties, by category PROPERTIES Colors color background-color Spacing margin padding margin-left, margin-right, margin-top, margin-bottom padding-left, padding-right, padding-top, padding-bottom Borders border-width border-style border-color border (to set the width, style, and color in one read more..

  • Page - 459

    APPENDIX A: ESSENTIAL CSS 439 THE ANATOMY OF A STYLE SHEET To do this, you need to give these elements a name with the class attribute. Here’s an example that creates a class named ArticleTitle: <h1 class="ArticleTitle">HTML5 is Winning</h1> Now you can write a style sheet rule that formats only this heading. The trick is to write read more..

  • Page - 460

    HTML5: THE MISSING MANUAL, SECOND EDITION 440 SLIGHTLY MORE ADVANCED STYLE SHEETS Slightly More Advanced Style Sheets You’ll see an example of a practical style sheet in a moment. But first you need to consider a few of the finer points of style-sheet writing. Structuring a Page with <div> Elements When working with style sheets, you’ll often use the read more..

  • Page - 461

    APPENDIX A: ESSENTIAL CSS 441 SLIGHTLY MORE ADVANCED STYLE SHEETS Multiple Selectors Sometimes, you might want to define some formatting that applies to more than one element or more than one class. The trick is to separate each selector with a comma. For example, consider these two heading levels, which have different sizes but share read more..

  • Page - 462

    HTML5: THE MISSING MANUAL, SECOND EDITION 442 SLIGHTLY MORE ADVANCED STYLE SHEETS <div class="Content"> ... <h2>Mayan Doomsday</h2> ... </div> In the first example, the first selector is a class selector, and the second selector (the contextual one) is an element type selector. However, you can change this up any read more..

  • Page - 463

    APPENDIX A: ESSENTIAL CSS 443 SLIGHTLY MORE ADVANCED STYLE SHEETS That means the ID selector is a good choice if you want to format a single, never- repeated element on your page. The advantage is that the ID selector clearly indicates the special importance of that element. For example, if a page has an ID selector named Menu or read more..

  • Page - 464

    HTML5: THE MISSING MANUAL, SECOND EDITION 444 SLIGHTLY MORE ADVANCED STYLE SHEETS Now an anchor element needs to specify the class name to display your new style, as shown here: <a class="BackwardLink" href="...">...</a> Pseudo-classes aren’t just a way to format links. The :hover pseudo-class is use- ful for applying animated read more..

  • Page - 465

    APPENDIX A: ESSENTIAL CSS 445 A STYLE SHEET TOUR A Style Sheet Tour Chapter 2 shows how you can learn to use HTML5’s semantic elements by revising a straightforward, but nicely formatted page called ApocalypsePage_Original.html (Figure A-1). This page links to a style sheet named ApocalypsePage_Original.css: <!DOCTYPE html> <html lang="en"> <head> read more..

  • Page - 466

    HTML5: THE MISSING MANUAL, SECOND EDITION 446 A STYLE SHEET TOUR First, the style sheet begins with a selector that targets the <body> element, which is the root of the entire web page. This is the best place to set inherited values that you want to apply, by default, to the rest of the document. Examples include margins, padding, read more..

  • Page - 467

    APPENDIX A: ESSENTIAL CSS 447 A STYLE SHEET TOUR Incidentally, every HTML color code can be written with the rgb() function, and vice versa. For example, you can write the color in the above example using the rgb() function, like this: background-color: rgb(118,149,254);  TIP  To actually get the RGB values for the color you want, try an online color read more..

  • Page - 468

    HTML5: THE MISSING MANUAL, SECOND EDITION 448 A STYLE SHEET TOUR This code works because the header contains two <span> elements. One <span> has the class name Teaser, and contains the subtitle. The second <span> has the author information, and uses the class name Byline. Here’s the relevant portion of markup: <div read more..

  • Page - 469

    APPENDIX A: ESSENTIAL CSS 449 A STYLE SHEET TOUR The next two rules change how the <h2> and <p> elements are formatted in the content region: .Content h2 { color: #24486C; margin-bottom: 2px; font-size: medium; } .Content p { margin-top: 0px; } As you can see, as a style sheet grows longer it doesn’t necessarily become more read more..

  • Page - 470

    read more..

  • Page - 471

    451 APPENDIX B There was a time when the Web was all about markup. Pages held text and HTML tags, and not much more. Really advanced websites used server scripts that could tweak the HTML markup before it made its way to the browser, but the code stopped there. Crack open a web page today and you’re likely to find buckets of JavaScript read more..

  • Page - 472

    HTML5: THE MISSING MANUAL, SECOND EDITION 452 HOW A WEB PAGE USES JAVASCRIPT How a Web Page Uses JavaScript Before you can run a line of JavaScript, you need to know where to put it in your web page. It all starts with the <script> element. The following sections show you how to take a page from quick-and-dirty JavaScript injection to read more..

  • Page - 473

    APPENDIX B: JAVASCRIPT: THE BRAINS OF YOUR PAGE 453 HOW A WEB PAGE USES JAVASCRIPT FIGURE B-1 When the web browser comes across JavaScript code, it runs it immediately. In fact, it even halts the page process- ing, temporarily. In this case, the code is held up until the web page user closes the message box by clicking OK. This al- lows the code to continue read more..

  • Page - 474

    HTML5: THE MISSING MANUAL, SECOND EDITION 454 HOW A WEB PAGE USES JAVASCRIPT Using a Function The problem with the previous example is that it encourages you to mingle code and markup in an unseemly mess. To keep things organized, you should wrap each code “task” in a function—a named unit of code that you can call into read more..

  • Page - 475

    APPENDIX B: JAVASCRIPT: THE BRAINS OF YOUR PAGE 455 HOW A WEB PAGE USES JAVASCRIPT parentheses. Inside the parentheses, you put whatever data the function needs. Or, if the function doesn’t accept any data, like showMessage(), you simply include parentheses with nothing inside them: ... <body> <p>At some point in the processing of this page, a read more..

  • Page - 476

    HTML5: THE MISSING MANUAL, SECOND EDITION 456 HOW A WEB PAGE USES JAVASCRIPT  NOTE  Virtually every well-designed web page that uses JavaScript puts the code in one or more script files. The only exceptions are if you have a few lines of very simple code that you’re certain not to use anywhere else, or if you’re creating a one-off example. Script files read more..

  • Page - 477

    APPENDIX B: JAVASCRIPT: THE BRAINS OF YOUR PAGE 457 HOW A WEB PAGE USES JAVASCRIPT You can also link to JavaScript functions on another website—just remember that the src attribute in the <script> element needs to point to a full URL (like http:// SuperScriptSite.com/MessageScript.js) instead of just a file name. This technique is necessary for read more..

  • Page - 478

    HTML5: THE MISSING MANUAL, SECOND EDITION 458 HOW A WEB PAGE USES JAVASCRIPT FIGURE B-2 In this example, the alert box doesn’t pop up until you move your mouse pointer over the link. TABLE B-1 Common HTML object events EVENT NAME DESCRIPTION APPLIES TO onClick Triggered when you click an element. Virtually all elements onMouseOver Triggered when you move your mouse read more..

  • Page - 479

    APPENDIX B: JAVASCRIPT: THE BRAINS OF YOUR PAGE 459 A FEW LANGUAGE ESSENTIALS EVENT NAME DESCRIPTION APPLIES TO onChange Triggered when you change a value in an input control. In a text box, this event doesn’t fire until you move to another control. <select>, <input type="text">, <textarea> onSelect Triggered when you select a portion of text in an input read more..

  • Page - 480

    HTML5: THE MISSING MANUAL, SECOND EDITION 460 A FEW LANGUAGE ESSENTIALS You can then use your variable: // Show the variable text in a message box. alert(myMessage);  NOTE  JavaScript is a notoriously loose language, and it lets you use variables even if you don’t specifically declare them with the var keyword. However, doing so is considered extremely bad form read more..

  • Page - 481

    APPENDIX B: JAVASCRIPT: THE BRAINS OF YOUR PAGE 461 A FEW LANGUAGE ESSENTIALS  TIP  The rule of thumb is to use a local variable, unless you specifically need to share your variable with multiple functions, or to retain its value after the function ends. That’s because it’s more trouble to keep track of global variables, and if you use too many, your read more..

  • Page - 482

    HTML5: THE MISSING MANUAL, SECOND EDITION 462 A FEW LANGUAGE ESSENTIALS TROUBLESHOOTING MOMENT Identifying Errors in JavaScript Code In order to deal with problems (like the variable mistake shown on page 461), you need to master debugging—the fine art of hunting down the problems in your code and stamping them out. Unfortunately, the read more..

  • Page - 483

    APPENDIX B: JAVASCRIPT: THE BRAINS OF YOUR PAGE 463 A FEW LANGUAGE ESSENTIALS var myText = "Hello"; var myText += " there."; // (Now myText is "Hello there.") And if you want to add or subtract the number 1, there’s an even more concise shortcut: var myNumber = 20; myNumber++; // (Now myNumber is 21.) myNumber--; // (Now myNumber is read more..

  • Page - 484

    HTML5: THE MISSING MANUAL, SECOND EDITION 464 A FEW LANGUAGE ESSENTIALS To use this condition to make decisions, you need to put it with an if statement. Here’s an example: if (myNumber < 100) { // (This code runs if myNumber is 20, but not if it's 147.) }  NOTE  Technically, you don’t need the curly brackets around your conditional code, read more..

  • Page - 485

    APPENDIX B: JAVASCRIPT: THE BRAINS OF YOUR PAGE 465 A FEW LANGUAGE ESSENTIALS and find the first one that matches (while ignoring the others), you need the else keyword. Here it is at work: if (myNumber < 100) { // (This code runs if myNumber is less than 100.) } else if (myNumber < 200) { // (This code runs if myNumber is less than 200 read more..

  • Page - 486

    HTML5: THE MISSING MANUAL, SECOND EDITION 466 A FEW LANGUAGE ESSENTIALS JavaScript arrays are remarkably flexible. Unlike in many other programming lan- guages, you don’t define the number of items you want an array to store in JavaScript. Instead, you simply begin by creating an empty array with square brackets, like this: var colorList = []; read more..

  • Page - 487

    APPENDIX B: JAVASCRIPT: THE BRAINS OF YOUR PAGE 467 A FEW LANGUAGE ESSENTIALS To add the parameter, you must first give it a name, say customMessage, and put it in parentheses after the function name, like so: function showMessage(customMessage) { alert(customMessage); }  NOTE  There’s no limit to how many pieces of information a function can accept. You read more..

  • Page - 488

    HTML5: THE MISSING MANUAL, SECOND EDITION 468 A FEW LANGUAGE ESSENTIALS Objects Virtually all modern programming languages include the concept of an object, which is a package of related data and features that you can interact with in code. For example, every HTML element on a web page is an object in the eyes of your code. Using the read more..

  • Page - 489

    APPENDIX B: JAVASCRIPT: THE BRAINS OF YOUR PAGE 469 A FEW LANGUAGE ESSENTIALS this.L_name = "Grapta"; } Now you can use the Person() function to create a new person object. The trick is that you don’t want to call the function and trigger its code. Instead, you want to create a new copy of the function by using the new keyword. read more..

  • Page - 490

    HTML5: THE MISSING MANUAL, SECOND EDITION 470 INTERACTING WITH THE PAGE var personObject = { firstName="Joe", lastName="Grapta" }; For each property, you specify the property name and its starting value. Thus, the above code sets personObject.firstName to the text “Joe” an d personObject. lastName to “Grapta.” The example on page read more..

  • Page - 491

    APPENDIX B: JAVASCRIPT: THE BRAINS OF YOUR PAGE 471 INTERACTING WITH THE PAGE The last two techniques require the XMLHttpRequest object, a JavaScript extension that’s described on page 377. In the following sections, you’ll take a look at the first of these, which is a fundamental part of almost every JavaScript-powered page. Manipulating an Element In read more..

  • Page - 492

    HTML5: THE MISSING MANUAL, SECOND EDITION 472 INTERACTING WITH THE PAGE This script works because it uses the property named innerHTML, which sets the content that’s nested inside an element (in this case, an <h1> element with the page title). Like all properties, innerHTML is just one aspect of an HTML object you can alter. To read more..

  • Page - 493

    APPENDIX B: JAVASCRIPT: THE BRAINS OF YOUR PAGE 473 INTERACTING WITH THE PAGE  TIP  HTML elements also provide a smaller set of useful methods, including some for modifying attributes, like getAttribute() and setAttribute(); and some for adding or removing elements, like insert- Child(), appendChild(), and removeChild(). To learn more about the properties and methods that a read more..

  • Page - 494

    HTML5: THE MISSING MANUAL, SECOND EDITION 474 INTERACTING WITH THE PAGE // This function runs when the onClick event happens. function swapImage() { var imgObject = document.getElementById("dayImage"); // Flip from day to night or night to day, and update the picture to match. if (dayTime === true) { dayTime = false; imgObject.src = read more..

  • Page - 495

    APPENDIX B: JAVASCRIPT: THE BRAINS OF YOUR PAGE 475 INTERACTING WITH THE PAGE The properties of the event object depend on the event. For example, the onMouse- Move event supplies the current mouse coordinates (which you’ll use when creating the painting program on page 263). There’s one more fine point to note. When you use code to connect an read more..

  • Page - 496

    HTML5: THE MISSING MANUAL, SECOND EDITION 476 INTERACTING WITH THE PAGE Finally, there’s one sort of inline function that’s used in many of the examples in this book. It’s the event handler for the window’s onLoad event, which fires after the entire page is rendered, displayed, and ready to go. This makes it a logical point for your read more..

  • Page - 497

    477 accessibility,  39 best practices, 39 canvas and, 274 video captions, 169–176 <acronym> element,  22 <address> element,  24 <a> element,  24 Android animation performance, 303 browser support for File API, 340 forms, 119 HTML5 audio formats, 153 HTML5 video formats, 153 IndexedDB, 353 server-sent events, 387 session history, 432 <track> element, 174 read more..

  • Page - 498

    INDEX 478 ARIA (ACCESSIBLE RICH INTERNET APPLICATIONS) recording, 145 Web Audio API, 145 <audio> element,  21, 143 adding sound effects, 161–164 autoplay attribute, 147 browser support for, 29 controlling players with JavaScript, 160–169 adding sound effects, 161–164 controls attribute, 146 empty syntax tags, 146 example of, 145–146 format fallbacks, 155–156 read more..

  • Page - 499

    INDEX 479 CANVAS <audio> element, 29 canvas and, 271–274 File API, 340 foreign elements in Internet Explorer, 52 geolocation feature, 413 HTML5 audio formats, 150, 153 HTML5 video formats, 151, 153 IndexedDB, 353 new input types in forms, 124–125 offline applications, 364–366 semantic elements, 51–53 server-sent events, 387 session history, 432 <track> element, 174 read more..

  • Page - 500

    INDEX 480 CANVAS ExplorerCanvas library, 271–272 Fabric.js, 258 fillEllipse() method, 258 filling shapes with patterns, 283–284 fill() method, 252–253 fillRect() method, 253, 256–257 fillStyle property, 252–253, 283 getContext() method, 247 getElementById() method, 246 getElementById() method and, 246 getting started, 246–263 globalAlpha property, 261 gradients, 281, 284–288 read more..

  • Page - 501

    INDEX 481 COMPOSITE OPERATIONS capitalization,  16 Captionator.js,  175 <center> element,  22 character encoding,  12–13 chess simulator,  315 Chrome audio/video playback controls, 146 browser support for File API, 340 HTML5 audio formats, 153 HTML5 video formats, 153 IndexedDB, 353 server-sent events, 387 session history, 432 <track> element, 174 validation, 119 web read more..

  • Page - 502

    INDEX 482 CONDITIONAL LOGIC transform functions, 203 transitions that use, 198, 204–206 transitions, 195–206, 385 basic, 196–198 gradients, 198 making more natural, 202 shadows, 198 that use transforms, 198, 204–206 transparency, 198 translateX(x) function, 203 translate(x, y) function, 203 translateY(y) function, 203 transparency, 185–187 vendor prefixes, 183–184 when an em read more..

  • Page - 503

    INDEX 483 FILE API E easier editing and maintenance,  38 echo server,  397–398 elements adapted, 22–24 added, 21 removed, 22 standardized, 25–26 tweaked, 24–25 ellipsis in book examples,  41 email data type,  124–125 <embed> element,  21, 25 <em> element,  23 em unit,  228 when an em becomes a rem, 230 enhanced search results,  94–98 EOT read more..

  • Page - 504

    INDEX 484 FILEREADER OBJECT fluid layouts,  222–226.  See also media queries adapting with media queries, 231– 244 max-width and min-width properties, 232 fluid typography,  228–230 <font> element,  22 font-family property,  438, 446 fonts creating font collections, 216 embedded font formats, 208 licensing, 211 subscription sites, 216 web.  See web fonts font-size read more..

  • Page - 505

    INDEX 485 GREATER THAN OR EQUAL TO (>=) how it works, 402–404 IP addresses, 402–403, 41 3 Manual Geolocation plug-in, 404 monitoring visitor’s moves, 413 showing a map, 409–412 why you should use it, 404 Geolocation object accuracy property, 407 browser compatibility and, 413 clearWatch() method (geolocation), 405, 413 coords object and, 405, 407–408, 412 read more..

  • Page - 506

    INDEX 486 H5O PLUG-IN smartphones and, 26 standard, 10 story of, 3–7 syntax, 16–21 tablet computers and, 26 three key principles of, 7–9 being practical, 9 “Don’t break the Web”, 7–8 “pave the cowpaths” approach, 8–9 using polyfills to fill HTML5 gaps, 35– 36 viewing, xiii–xiv vs. HTML, xv writing, xiii HTML5Forms library,  122 HTML Canvas,  315 HTML read more..

  • Page - 507

    INDEX 487 ITEMREVIEWED PROPERTY “Insufficient data to generate the preview” error message,  96 interactivity elements,  21 Internet Explorer alert( ) function, 453 audio/video playback controls, 146 browser support for File API, 340 HTML5 audio formats, 153 HTML5 video formats, 153 IndexedDB, 353 server-sent events, 387 session history, 432 <track> element, 174 read more..

  • Page - 508

    INDEX 488 JAVASCRIPT getCurrentPosition() method, 405, 407, 409, 413, 470 getElementById() method, 471 hiding element that wraps footer, 61 how web pages use, 452–459 HTML5 features that require, 375 inline events, 475–476 insertChild() method, 473 interacting with offline applications, 371–374 interacting with pages, 470–476 jQuery UI, 201 JS API group, 28 read more..

  • Page - 509

    INDEX 489 LESS THAN OR EQUAL TO (<=) ignoreDrag(), 338 importScripts(), 420 inline, 475, 475–476 linear-gradient(), 193 LinkRecord(), 347 naming, 457 Number(), 325, 328–329 object-definition, 468–469 processFiles(), 334, 336, 339 receiving and returning data, 466– 467 rgb(), 446–447 canvas, 250, 260 rgba(), 260 setInterval(), 386 animation, 301 web workers and, 414, 424–425 read more..

  • Page - 510

    INDEX 490 LETTER- SPACING PROPERTY max-width media feature, 233–242 @media block, 239–241 more advanced query conditions, 239–241 most useful features for building, 233–234 orientation media feature, 234–235, 238, 242–244 recognizing specific mobile devices, 242–244 replacing entire style sheet, 241–242 <menu> element,  21, 135 metadata <audio> element, 146 read more..

  • Page - 511

    INDEX 491 ONLINE HTML OUTLINER LinkRecord, 342–343, 347–348 literals, 469–470 naming, 457 navigator, 405 storing, 329–330 WebSocket creating, 395–397 detecting failed connection, 397 socket-connection code, 397 offline application feature,  355–374 browser support for, 364–366 browser support for offline applications, 364–366 bypassing cache when online, 370 caching and query read more..

  • Page - 512

    INDEX 492 ONLOAD EVENT P padding-bottom property,  438 padding-left property,  438 padding properties,  448 padding property,  438 padding-right property,  438 padding-top property,  438 page redirect,  432 page structure,  37–74, 75 elements, 76 nested structure and microdata, 90 the old way, 40–43 page structuring elements,  21 Paper.js,  307 parentElement property,  472 read more..

  • Page - 513

    INDEX 493 <SELECT> ELEMENT <rp> element,  21 RSS feeds,  93 <rt> element,  21 <ruby> element,  21 Ruby web socket server,  399 running applications offline.   See offline application feature S Safari browser support for File API, 340 HTML5 audio formats, 153 HTML5 video formats, 153 IndexedDB, 353 server-sent events, 387 session history, 432 <track> read more..

  • Page - 514

    INDEX 494 SELECTORS, CONTEXTUAL goToNewSlide() function, 430 hashbang URLs, 427–428 onPopState event, 429, 430, 431 pushState() method, 426, 429–430 replaceState() method, 431 server-side includes and, 431 templates and, 431 three basic methods, 425 URL problem, 426 sidebars,  56–59.  See also <aside> element complex, 58 shaping into three sections, 57 Silverlight,  151 read more..

  • Page - 515

    INDEX 495 VIDEO offline application feature, 362 <tt> element,  22 TTF (TrueType),  207–208, 21 0 U url data type,  124, 126 URLs changing to anything you like.  See session history creating extra pages to satisfy, 431 data URLs, 268–271 hashbang, 427–428 UTF-8 encoding,  13 V validation,  17–19 blank values and, 117 browser support for, 119 forms, 112–119 read more..

  • Page - 516

    INDEX 496 <VIDEO> ELEMENT preloading, 146–147 recording, 145 single page for desktop browsers and mobile devices, 156 subtitles, 169–175 adding, 172–173 search engines and, 173 timed text tracks, 170 versus captions, 173 WebVTT file, 170–176 VideoJS player, 167–169 YouTube, 157 Zencoder, 156 <video> element,  21, 38 adding subtitles with <track> read more..

  • Page - 517

    INDEX 497 WEB WORKERS WebSocket objects creating, 395–397, 397 detecting failed connection, 397 socket-connection code, 397 web sockets,  375, 393 browser support for, 394 checking support for, 394 echo server, 397–398 examples on the web, 397–400 simple client, 395–397 web socket server, 394–395 web socket servers, 399 Web SQL Database,  353 web storage,  319–354.  See read more..

  • Page - 518

    INDEX 498 WEEK DATA TYPE XHTML5 validator,  20 XMLHttpRequest objects,  105, 133, 138, 140, 377, 430 asking the web server a question, 377–382 calling the web server, 380–382 getting new content, 382–386 goToNewSlide() function, 384 onReadyStateChange event, 380– 381 query string, 379 sending messages to web server, 376 send() method, 381, 396 web workers and, 424 read more..

  • Page - 519

    Don’t miss a thing! Sign up for the free Missing Manual email announcement list at missingmanuals.com. We’ll let you know when we release new titles, make free sample chapters available, and update the features and articles on the Missing Manual website. HTML5 TH E MIS SING CD There’s no CD with this book; you just saved $5.00. read more..

Write Your Review