Free Download PDF Books, Introducing HTML5 2nd Edition

Introducing HTML5 2nd Edition

HTML HTML5 ReadOnline

Summary of Contents

  • Page 1

    ptg6964689actionURI(https://freepdf-books.com ):https://freepdf-books.com

  • Page 2

    ptg69646895HTMLINTRODUCINGSECONDEDITIONBRUCE LAWSONREMY SHARPactionURI(https://freepdf-books.com ):https://freepdf-books.com

  • Page 3

    ptg6964689Introducing HTML5, Second EditionBruce Lawson and Remy SharpNew Riders1249 Eighth StreetBerkeley, CA 94710510/524-2178510/524-2221 (fax)Find us on the Web actionURI(www.newriders.com):at: www.newriders.comTo report errors, please send a note to errata@peachpit.comNew Riders is an imprin...

  • Page 4

    ptg6964689ACKNOWLEDGEMENTSHuge thanks to coauthor-turned-friend Remy Sharp, and friend-turned-ruthless-tech-editor Patrick Lauke: il miglior fabbro. At New Riders, Michael Nolan, Margaret Anderson, Gretchen Dyk-stra, and Jan Seymour deserve medals for their hard work and their patience.Thanks to ...

  • Page 5

    ptg6964689AckNowLEdgEMENTSivStu Robson braved IE6 to take the screenshot in Chapter 1, Terence Eden took the BlackBerry screenshots in Chapter 3, Julia Gosling took the photo of Remy’s magic HTML5 moustache in Chapter 4, and Jake Smith provided valuable feedback on early drafts of my chapters. ...

  • Page 6

    ptg6964689AckNowLEdgEMENTSvTo the HTML5 Doctors and Rich Clark in particular for invit-ing me to contribute—and also to the team for publishing such great material.To the whole #jquery-ot channel for their help when I needed to debug, or voice my frustration over a problem, and for being some...

  • Page 7

    ptg6964689CONTENTS 10,Introduction 10, 10,ix 18,CHAPTER 18,1 18, 18,Main Structure 18,1 19,The <head> 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19...

  • Page 8

    ptg6964689coNTENTSvii 122,Avoiding 122, validation 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 105 125...

  • Page 9

    ptg6964689coNTENTSviii 242,CHAPTER 242,8 242, 242,Drag and Drop 242,225 243,Getting into drag 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 2...

  • Page 10

    ptg6964689 7,INTRODUCTIONWelcome to the second edition of the Remy & Bruce show. Since the first edition of this book came out in July 2010, much has changed: support for HTML5 is much more widespread; Internet Explorer 9 finally came out; Google Chrome announced it would drop support for H.2...

  • Page 11

    ptg6964689INTRoducTIoNxStill here? Good.What this book isn’tThis is not a reference book. We don’t go through each element or API in a linear fashion, discussing each fully and then moving on. The specification does that job in mind-numbing, tear-jerking, but absolutely essential detail.What ...

  • Page 12

    ptg6964689INTRoducTIoNxiWho? What? When? Why? A short history of HTML5History sections in computer books usually annoy us. You don’t need to know about ARPANET or the history of HTTP to under-stand how to write a new language. Nevertheless, it’s useful to understand how HTML5 came about, beca...

  • Page 13

    ptg6964689INTRoducTIoNxiithis genesis still in the copyright notice on the WHATWG ver-sion of the spec “© Copyright 2004–2011 Apple Computer, Inc., Mozilla Foundation, and Opera Software ASA (note that you are licensed to use, reproduce, and create derivative works).”Hickson moved to Googl...

  • Page 14

    ptg6964689INTRoducTIoNxiiiThe process has been highly unusual in several respects. The first is the extraordinary openness; anyone could join the WHATWG mailing list and contribute to the spec. Every email was read by Hickson or the core WHATWG team (which included such luminaries as the inventor...

  • Page 15

    ptg6964689INTRoducTIoNxivNot breaking existing web pages Many of our current methods of developing sites and applications rely on undocumented (or at least unspecified) features incorporated into browsers over time. For example, XMLHttpRequest (XHR) powers untold numbers of Ajax-driven sites. It...

  • Page 16

    ptg6964689INTRoducTIoNxvWeb applications An increasing number of sites on the Web are what we’ll call web applications; that is, they mimic desktop apps rather than traditional static text-images-links documents that make up the majority of the Web. Examples are online word processors, photo-ed...

  • Page 17

    ptg6964689INTRoducTIoNxvifeatures, but (unsurprisingly) requires a more rigid syntax (if you’re used to coding XHTML, this is exactly the same as you already write). It must be well-formed XML and it must be served with an XML MIME type, even though IE8 and its antecedents can’t process it (i...

  • Page 18

    ptg6964689 7,CHAPTER 1 7,Main StructureBruce LawsonALTHougH MucH oF the attention that HTML5 has received revolves around the new APIs, there is a great deal to interest markup monkeys as well as JavaScript junkies. There are 30 new elements with new semantics that can be used in traditional “...

  • Page 19

    ptg6964689INTRoducINg HTML52 7,The <head> First things first: the DOCTYPE: <!DOCTYPE html> That’s it. No unwieldy string that even the most prolific web authors need to cut and paste. No URLs. No version number. That’s all. It’s not so much an instruction as an incantation: it...

  • Page 20

    ptg6964689cHApTER 1 : MAIN STRucTuRE : THE <HEAd> 3Pick a style and stick with itJust because you can use any of the aforementioned syntaxes doesn’t mean you should mix them all up, however. That would prove a maintenance nightmare, particularly in a large team. Our advice is to pick a st...

  • Page 21

    ptg6964689INTRoducINg HTML54This is perhaps one of those WTF? moments I mentioned in the introduction. These three elements are (XHTML authors, are you sitting down?) entirely optional, because browsers assume them anyway. A quick glance under the browser hood with Opera Dragonfly confirms this (...

  • Page 22

    ptg6964689cHApTER 1 : MAIN STRucTuRE : THE <HEAd> 5IE8 and below require the <body> element before they will apply CSS to style new HTML5 elements, so it makes sense to use this element, too.So, in the interest of maintainability, we’ll add those optional elements to make what’s p...

  • Page 23

    ptg6964689INTRoducINg HTML56 7,Using new HTML5 structural 7,elements In 2004, Ian Hickson, the editor of the HTML5 spec, mined one billion web pages via the Google index, looking to see what the “real” Web is made of. One of the analyses he subse-quently published (actionURI(http://code.goog...

  • Page 24

    ptg6964689cHApTER 1 : MAIN STRucTuRE : uSINg NEw HTML5 STRucTuRAL ELEMENTS 7As you can see, once we remove obviously presentational classes, we’re left with a good idea of the structures that authors are trying to use on their pages. Just as HTML 4 reflects the early Web of scientists and engi-...

  • Page 25

    ptg6964689INTRoducINg HTML58Diagrammatically, the page looks like Figure 1.4.div id="header"div class="post"div class="post"div id="footer"div id= "side- bar"While there is nothing at all wrong with this markup (and it’ll continue working perfec...

  • Page 26

    ptg6964689cHApTER 1 : MAIN STRucTuRE : uSINg NEw HTML5 STRucTuRAL ELEMENTS 9 <li><a href=”archive.html”>Archives</a></li> </ul> </nav> <article> <h2>Yesterday</h2> <p>Today I drank coffee for breakfast. 14 hours later, ¬ I wen...

  • Page 27

    ptg6964689INTRoducINg HTML510Why, oh why, is there no <content> element?It’s easy to see how our hypothetical “jump to nav” shortcut key would work, but a more common require-ment is to jump straight to the main content area. Some accessibility-minded designers add a “skip links” ...

  • Page 28

    ptg6964689cHApTER 1 : MAIN STRucTuRE : STYLINg HTML5 wITH cSS11properly in ye olde browsers until we explicitly tell the browser that they are display:block. Browsers contain a rudimentary, built-in style sheet that overrides the default inline styling for those elements we think of as natively b...

  • Page 29

    ptg6964689INTRoducINg HTML512CSS, HTML5, and JavaScript does. IE9 works like the other browsers and doesn’t need JavaScript.Although this JavaScript is unnecessary for other brows-ers, it won’t cause them any harm. However, you might wish to give your page a speed optimisation and only downlo...

  • Page 30

    ptg6964689cHApTER 1 : MAIN STRucTuRE : wHEN To uSE THE NEw HTML5 STRucTuRAL ELEMENTS 13 7,When to use the 7,new HTML5 7,structural elements We’ve used these elements to mark up our page, and styled them, and although the use of each might seem to be self-evident from the names, it’s time to...

  • Page 31

    ptg6964689INTRoducINg HTML514The header can also contain navigation. This can be very use-ful for site-wide navigation, especially on template-driven sites where the whole of the <header> element could come from a template file. So, for example, the horizontal site-wide navigation on action...

  • Page 32

    ptg6964689cHApTER 1 : MAIN STRucTuRE : wHEN To uSE THE NEw HTML5 STRucTuRAL ELEMENTS 15 <li>Home</li> <li><a href=”courses.html”>Cookery Courses</a></li> <li><a href=”contact.html”>Contact</a></li> </ul></nav> It d...

  • Page 33

    ptg6964689INTRoducINg HTML516To <nav> or not to <nav>?I was previously guilty of navitis—the urge to surround any links to other parts of a site as <nav>. I cured myself of it by considering who will benefit from use of the <nav> element. We’ve previously spec-ulated a...

  • Page 34

    ptg6964689cHApTER 1 : MAIN STRucTuRE : wHEN To uSE THE NEw HTML5 STRucTuRAL ELEMENTS 17While it makes sense to use a list (and it gives you more hooks for CSS), it’s not mandatory. This is perfectly valid:<nav> <p><a href=”/”>Home</a></p> <p><a href=...

  • Page 35

    ptg6964689INTRoducINg HTML518<aside> <nav> <h2>Pages</h2> <ul> .. </ul> <h2>Categories</h2> <ul> .. </ul> <h2>Recent comments</h2> <ul> ... </ul></nav> <section> <h2>blah blah</h2>...;

  • Page 36

    ptg6964689cHApTER 1 : MAIN STRucTuRE : wHEN To uSE THE NEw HTML5 STRucTuRAL ELEMENTS 19The spec continues, “A footer typically contains information about its section, such as who wrote it, links to related docu-ments, copyright data, and the like.”Our footer holds copyright data, which we’r...

  • Page 37

    ptg6964689INTRoducINg HTML520email client, maps, and reusable web widgets. For <article>don’t think newspaper article, think article of clothing—a discrete item. Note that, as with <nav>, the heading is part of the article itself, so it goes inside the element. Thus<h1>My ar...

  • Page 38

    ptg6964689cHApTER 1 : MAIN STRucTuRE : SuMMARY21search engine could weight links in a footer less highly than links in a nav bar. There are many future uses that we can’t guess at—but they all depend on unambiguously assigning meaning to content, which is the definition of semantic markup. 7,...

  • Page 39

    ptg6964689This page intentionally left blank https://freepdf-books.com

  • Page 40

    ptg6964689 7,CHAPTER 2 7,TextBruce LawsonNow THAT You’VE marked up the main page land-marks with HTML5 and seen how a document’s outline can be structured, this lesson looks deeper to show how you can further structure your main content.To do this, you’ll mark up a typical blog with HTML5. ...

  • Page 41

    ptg6964689INTRoducINg HTML524 7,Structuring main content 7,areasTake a look at the main content area of a blog (Figure 2.1). There may be multiple articles, each containing metadata and the actual textual content of that article. Here’s some typical markup (simplified from the default WordPres...

  • Page 42

    ptg6964689cHApTER 2 : TExT : STRucTuRINg MAIN coNTENT AREAS25HTML 4 gives us generic structures to mark up content. <div>, for example, is just a generic box that tells the browser, “Here’s some stuff, it all belongs together,” but it doesn’t mean anything; there’s no semantic val...

  • Page 43

    ptg6964689INTRoducINg HTML526The <time> elementThe new element <time> is used for unambiguously encod-ing dates and times for machines, while still displaying them in a human-readable way. The uses of this in web pages aren’t hard to imagine: a browser could offer to add future even...

  • Page 44

    ptg6964689cHApTER 2 : TExT : STRucTuRINg MAIN coNTENT AREAS27Reddit.com combines a relative time (“8 hours ago”) as the text content of the element, with a title attribute showing the human-readable full time on hover: <p>Submitted <time title=”Sun Jul 3 02:15:49 2011 GMT” ¬ da...

  • Page 45

    ptg6964689INTRoducINg HTML528You might be wondering why the pubdate attribute is needed at all. Why not just assume that any <time> element in an <article>’s <header> is its publication date?Consider this example:<article> <header> <h1>Come to my party on...

  • Page 46

    ptg6964689cHApTER 2 : TExT : STRucTuRINg MAIN coNTENT AREAS29Using multiple <footer>s on the same element The spec says, “Footers don’t necessarily have to appear at the end of a section, though they usually do,” and it allows an ele-ment to have two or more footers. A simplified vers...

  • Page 47

    ptg6964689INTRoducINg HTML530 7,Adding blog posts 7,and commentsSo, you have a page with a header, footer, navigation, and content areas containing several articles (blog posts), each with its own header and footer. But wait...what is a blog without comments?The specification mentions this case...

  • Page 48

    ptg6964689cHApTER 2 : TExT : woRkINg wITH HTML5 ouTLINES31 <p>I’m throwing a party at Dr Einstein’s Cabaret ¬ Roller-disco Bierkeller Pizza-parlour-a-gogo. Do come ¬ and dance to Rusty Trombone’s Swingin’ Brass Band. ¬ (Formal dress and lewd hat required.)</p><foo...

  • Page 49

    ptg6964689INTRoducINg HTML532HTML5 has a tightly defined outlining algorithm that allows user agents to produce a similar outline from a web page. Just as with a word-processing package, this could be used to give the user a quick overview of the web page (and, of course, there’s no reason why ...

  • Page 50

    ptg6964689cHApTER 2 : TExT : woRkINg wITH HTML5 ouTLINES33<article> has started a new section. Using <section>, <nav>, or <aside> instead of <article> does the same thing, as they are all sectioning content.In fact, it doesn’t matter what level of heading you use h...

  • Page 51

    ptg6964689INTRoducINg HTML534Let’s say you run a large online newspaper and naturally wish to syndicate this story. When the magic syndication machines slot it into your template, the resulting code is<h1>The Monotonous Times</h1><section> <h2>Breaking news</h2> &...

  • Page 52

    ptg6964689cHApTER 2 : TExT : woRkINg wITH HTML5 ouTLINES35such as “Most popular posts” or “Recent comments,” but you probably don’t want a heading on your main site <nav> that just says “Navigation.” Therefore, if you see “Untitled Section,” don’t automatically assume t...

  • Page 53

    ptg6964689INTRoducINg HTML536Sectioning rootsNote that certain elements—<blockquote>, <body>, <details>, <fieldset>, <figure>, <td>—are said to be sectioning roots, and can have their own outlines, but the sections and headings inside these elements do not ...

  • Page 54

    ptg6964689cHApTER 2 : TExT : woRkINg wITH HTML5 ouTLINES37Styling headings in HTML5All this clever stuff presents a challenge to authors of CSS. Given that<article><section><h1>...</h1></section></article><article><article><h1>...</h1>&l...;

  • Page 55

    ptg6964689INTRoducINg HTML538have keyboard shortcuts that allow users to jump from heading to heading. For example, the JAWS screen reader (by far the most used package, according to the survey) uses the H key to jump from heading to heading, the 1 key to jump to the next <h1>, the 2 key to...

  • Page 56

    ptg6964689cHApTER 2 : TExT : woRkINg wITH HTML5 ouTLINES39<article>Consider this real-world blog/news article:<article><h1>Bruce Lawson Is World’s Sexiest Man</h1><p>Legions of lovely ladies voted luscious lothario Lawson ¬ as the World’s Sexiest Man today.</...

  • Page 57

    ptg6964689INTRoducINg HTML540As you’ve seen, comments on blog posts are <article>s inside a parent <article>. There are other uses for this nesting besides comments—for example, a transcript to a video:<article><h1>Stars celebrate Bruce Lawson</h1><video>.....

  • Page 58

    ptg6964689cHApTER 2 : TExT : woRkINg wITH HTML5 ouTLINES41Does the “Vital caveat about the information above” refer to the whole article, that is, everything under the introductory <h1>, or does it refer only to the information under the preceding <h2>(“Fan Club uniforms”)? In...

  • Page 59

    ptg6964689INTRoducINg HTML542If it had been inside the final section element<article>...<section> <h2>Fan Club uniforms</h2> <p>All Munchkins are obliged to wear their “I’m a friend ¬ of Dorothy!” t-shirt when representing the club</p> <p><...

  • Page 60

    ptg6964689cHApTER 2 : TExT : woRkINg wITH HTML5 ouTLINES43the HTML5 outlining algorithm (whereas <div> doesn’t, because it has no special structural meaning). <section><h1>Articles about llamas</h1><article><h2>The daily llama: Buddhism and South American ca...

  • Page 61

    ptg6964689INTRoducINg HTML544Estelle Weyl has a good analogy actionURI(www.standardista.com/html5-section-v-article):at actionURI(www.standardista.com/html5-section-v-article):www.standardista.com/actionURI(www.standardista.com/html5-section-v-article):html5-section-v-article: “Think of a news...

  • Page 62

    ptg6964689cHApTER 2 : TExT : woRkINg wITH HTML5 ouTLINES45The following is how I would mark up this page; you might choose different structures, and that’s OK. There’s not necessar-ily “one true way” of doing this; it depends in part on how you intend to use the content—will you syndica...

  • Page 63

    ptg6964689INTRoducINg HTML546Aside from the JavaScript-controlled ticker effect, this “breaking news” is simply a list of links to other pages. Therefore, it matches the <nav> element. Don’t be fooled by the fact that it’s horizontal, with the heading on the same line; CSS will sort...

  • Page 64

    ptg6964689cHApTER 2 : TExT : woRkINg wITH HTML5 ouTLINES47Our navigation is a single <nav> element containing multiple unordered lists—each with its own heading (Jobs, Dating, CD box sets, Today’s paper, and so on), styled with a blue-grey background and a thick red border-top. However,...

  • Page 65

    ptg6964689INTRoducINg HTML548a list of <article>s. Because <section> isn’t appropriate here, if there is a need to wrap all the articles with an element for styl-ing purposes, you’d use the semantically empty <div> element.There is one featured article that consists mostly o...

  • Page 66

    ptg6964689cHApTER 2 : TExT : uNdERSTANdINg wAI-ARIA 49</section><section><h2>Latest multimedia</h2>...</section>On the website (but not in the screenshot), there are also a cou-ple more <nav> blocks (“Trending,” “Campaigns and investiga-tions”) and a ...

  • Page 67

    ptg6964689INTRoducINg HTML550So, using horrible old-school HTML you could—in theory—add ARIA to<font size=”+5” color=”red”>I should be a heading</font>to make<font size=”+5” color=”red” role=”heading” aria-level=”2”> ¬ I should be a heading</font&...

  • Page 68

    ptg6964689cHApTER 2 : TExT : uNdERSTANdINg wAI-ARIA 51ARIA document structure and landmark rolesWAI-ARIA defines several roles that tell assistive technology about landmarks and the structure of a document. Some of these are:• application• article• banner• complementary• contentinfo• ...

  • Page 69

    ptg6964689INTRoducINg HTML552Similarly, contentinfo is defined as “a large perceivable region that contains information about the parent document. Examples of information included in this region of the page are copyrights and links to privacy statements.” This sounds like <footer>, but ...

  • Page 70

    ptg6964689cHApTER 2 : TExT : EVEN MoRE NEw STRucTuRES!53Enhancement: Building the Web that Works for Everyone by Todd Parker, et al. (New Riders) for useful information on practi-cal uses of ARIA. The ARIA spec itself is at actionURI(www.w3.org/WAI/PF/aria/):www.w3.org/WAI/PF/aria/.A note on scre...

  • Page 71

    ptg6964689INTRoducINg HTML554HTML5 element categories and content models HTML 4 divided elements into “block-level” and “inline.” These names are gone from HTML5, as they’re inherently presentational; they simply reflect the way browsers display them with their default style sheets. The...

  • Page 72

    ptg6964689cHApTER 2 : TExT : EVEN MoRE NEw STRucTuRES!55<div itemscope itemtype=”http://schema.org/Book”>I love that Introducing HTML5 by Bruce Lawson and Remy Sharp ¬ (ISBN 0321784421)</div>Using itemprop I can assign properties to the content:<div itemscope itemtype=”htt...

  • Page 73

    ptg6964689INTRoducINg HTML556<div itemscope itemtype=”http://schema.org/Book”>I love that <span itemprop=”name”>Introducing HTML5</span> By<span itemprop=”author” itemscope itemtype= ¬ ”http://microformats.org/profile/hcard”> <span itemprop=”fn”>...;

  • Page 74

    ptg6964689cHApTER 2 : TExT : EVEN MoRE NEw STRucTuRES!57specified, and must not be specified on elements with an item-scope attribute whose itemtype attribute specifies a vocabulary that does not support global identifiers for items, as defined by that vocabulary’s specification.” For more in...

  • Page 75

    ptg6964689INTRoducINg HTML558<bdi>The spec says that <bdi> “represents a span of text that is to be isolated from its surroundings for the purposes of bidirectional text formatting.” Huh? I asked Richard Ishida (@r12a on Twitter—follow him!), the W3C’s internationalization lea...

  • Page 76

    ptg6964689cHApTER 2 : TExT : EVEN MoRE NEw STRucTuRES!59You’ll notice that the example above has bdi around the name Aroma too. Of course, you don’t actually need that, but it won’t do any harm. On the other hand, it means you can write a script in something like PHP that says:foreach $rest...

  • Page 77

    ptg6964689INTRoducINg HTML560<details> <summary>Photograph details</summary> <p>Photograph taken on <time datetime=2009-12-25>Xmas ¬ Day 09</time> with a Canon IXUSi.</p> <p><small>Copyright Bruce Lawson, ¬ <address>bruce@brucelawson...

  • Page 78

    ptg6964689cHApTER 2 : TExT : EVEN MoRE NEw STRucTuRES!61Styling this markup can produce some nice effects (Figure 2.21). Notice that there is no alt attribute on the image. In the first edition, I had added a blank alt="", but this was incorrect. In figures where the figcaption text tel...

  • Page 79

    ptg6964689INTRoducINg HTML562On the other hand, you may think that the example above needs alt text <img src=welcome.jpg alt=”Bruce and Remy glower menacingly into the camera”> because otherwise the joke isn’t communicated to a screen reader user.As an accessibility bonus it’s usef...

  • Page 80

    ptg6964689cHApTER 2 : TExT : EVEN MoRE NEw STRucTuRES!63<mark>The <mark> element allows you to do the markup equivalent of using a highlighter pen to bring out some words on a printed page. It’s not the same as emphasis—for that you use <em>. But if you had some existing tex...

  • Page 81

    ptg6964689INTRoducINg HTML564To help the reader, sometimes the pronunciation is written above the kanji using the hiragana alphabet. This is called furig-ana in Japanese and ruby in English (from the name of the small 5.5 pt type size used for similar sorts of annotations in British print tradi...

  • Page 82

    ptg6964689cHApTER 2 : TExT : REdEFINEd ELEMENTS65 7,Redefined elementsHTML5 redefines the semantics of some existing elements as well as adding new ones. Here are a few old friends: some have radically changed, others have simply finessed their hairstyles.<address>As in HTML4, <address&g...;

  • Page 83

    ptg6964689INTRoducINg HTML566<cite>In HTML 4, the <cite> element could be used to mark up the name of a speaker: As <cite>Harry S. Truman</cite> said,<Q lang=”en-us”> ¬ The buck stops here.</Q>HTML5 disallows this: “A person’s name is not the title of ...

  • Page 84

    ptg6964689cHApTER 2 : TExT : REdEFINEd ELEMENTS67 <dd>Helen Bach</dd> <dt>The Proctologist and the Dentist</dt> <dd>Ben Dover</dd> <dd>Phil McCavity</dd> </dl><em>, <i>Use <em> to mark up emphasis of the kind that subtly ...

  • Page 85

    ptg6964689INTRoducINg HTML568Unless your audience has significant numbers of users of these phones, we recommend you use sectioning content and head-ings instead, with CSS for pretty dividers and forget about <hr>. That way you have less markup, and besides, it’s hard to style <hr> ...

  • Page 86

    ptg6964689cHApTER 2 : TExT : REdEFINEd ELEMENTS69<small>The <small> element has been completely redefined, from a generic presentational element to make text appear smaller to actually representing “small print,” which “typically features disclaimers, caveats, legal restrictions...

  • Page 87

    ptg6964689INTRoducINg HTML570The spec says it “represents a span of text with an unarticulated, though explicitly rendered, non-textual annotation, such as label-ing the text as being a proper name in Chinese text (a Chinese proper name mark), or labeling the text as being misspelt.”Removed e...

  • Page 88

    ptg6964689cHApTER 2 : TExT : gLoBAL ATTRIBuTES71explaining that “the search field is given two possible access keys, ‘s’ and ‘0’ (in that order). A user agent on a device with a full keyboard might pick Ctrl+Alt+S as the shortcut key, while a user agent on a small device with just a num...

  • Page 89

    ptg6964689INTRoducINg HTML572data-* (custom data attributes)HTML5 allows custom attributes on any element. These can be used to pass information to local scripts.Previously, to store custom data in their markup, authors would do something annoying like use classes: <input class=”spaceship sh...

  • Page 90

    ptg6964689cHApTER 2 : TExT : gLoBAL ATTRIBuTES73 var attributes = el.attributes, values = [];for (var i = 0; i < attributes.length; i++) { if (attributes[i].name.indexOf(‘data-’) === 0) { values.push(test.attributes[i].nodeValue); }}When fully implemented in browsers, setting a da...

  • Page 91

    ptg6964689INTRoducINg HTML574Even if you know that you’ll be “unhiding” stuff later with some scripting, you should treat hidden stuff as if it literally wasn’t there. So don’t add links pointing to content that’s hidden and don’t tie other elements to it with aria-describedby or ar...

  • Page 92

    ptg6964689cHApTER 2 : TExT : REMoVEd ATTRIBuTES75rendering order and logical tab order. Because no one above the level of WYSIWYG-wielding wannabe has used tables for layout since Mozart went stegosaurus hunting, nowadays this is not usually necessary. The default tab order is determined by the o...

  • Page 93

    ptg6964689INTRoducINg HTML576not also get marked as presentational in the eyes of screen-readers and other ARIA-consuming user agents.Of course, if you need groovy borders for your data tables, use CSS. This is really here just for backwards compatibility.<table summary=...>Previous version...

  • Page 94

    ptg6964689cHApTER 2 : TExT : FEATuRES NoT coVEREd IN THIS Book77 7,Features not covered in 7,this bookFor completeness, here are some of the most interesting fea-tures of HTML5 that, for reasons of page count or lack of imple-mentation, aren’t discussed further.<embed>Of course <embed...

  • Page 95

    ptg6964689INTRoducINg HTML578<style scoped>The scoped attribute on a style element tells the browser to apply the styles to the element that the <style scoped> element is in, and its children. Thus, it is found inside elements in the document’s <body> rather than only in the ...

  • Page 96

    ptg6964689 7,CHAPTER 3 7,FormsBruce LawsonoNE oF THE problems with HTML 4 forms is that they’re just dumb fields. Validation is required on the server, of course, but you have to duplicate it in the user’s browser with JavaScript to give them the seamless experience they deserve. Given that a...

  • Page 97

    ptg6964689INTRoducINg HTML580 7,We 7, 7, HTML, and now it 7,s us backHTML5 makes developing forms quicker. There are some nice goodies like the addition of two HTTP types of form action (update and delete) to go with the current get and post. But the coolest features for developers—which will...

  • Page 98

    ptg6964689cHApTER 3 : FoRMS : NEw INpuT TYpES81The manner in which the browser reports errors is similarly unde-fined. Figure 3.2 shows errors generated when a required field isn’t completed before submission in Opera, Firefox, and Google Chrome. Below, you can see the same error in the Japanes...

  • Page 99

    ptg6964689INTRoducINg HTML582Currently browsers aren’t this helpful, but because this type is now unambiguous and machine readable/understandable, the browser knows what the intention of the author is and can con-ceivably offer more contextually-relevant UI. For example, the experimental Firefo...

  • Page 100

    ptg6964689cHApTER 3 : FoRMS : NEw INpuT TYpES83FIguRE 3.3 Opera renders a calendar widget.FIguRE 3.4 <input type=date> on the BlackBerry browser.Of course, these are still early days. In the future, though, it’s conceivable that, beyond simply showing a shiny new datepicker, the browser...

  • Page 101

    ptg6964689INTRoducINg HTML584The month input type Using <input type=month> allows entry and validation of a month. Although the month value is stored internally as a number between 1 and 12, the browser may offer a selection method that uses the names of the months instead. You could do thi...

  • Page 102

    ptg6964689cHApTER 3 : FoRMS : NEw INpuT TYpES85It works perfectly with the min, max, and step attributes (see below). In Opera and Chrome, it is rendered as a spinner con-trol that will not go beyond the upper and lower limits (if speci-fied) and which progresses by the increment specified in ste...

  • Page 103

    ptg6964689INTRoducINg HTML586The search input typeThis input type, <input type=search>, expects a search term. In Safari there is also an unspecified proprietary attribute that adds a history of recent results, using the results=n attribute. The difference between search and text type is on...

  • Page 104

    ptg6964689cHApTER 3 : FoRMS : NEw ATTRIBuTES87The color input type<input type=color> allows the user to input a colour value via a picker. So far, it’s only implemented on the BlackBerry (Figure 3.9) and Opera. Don’t forget the name attribute!Just because new client-side validation is b...

  • Page 105

    ptg6964689INTRoducINg HTML588The list is contained in a new <datalist> element, the id of which is referenced in the value of the list attribute: <input id=form-person-title type=text list=mylist> <datalist id=mylist> <option label=Mr value=Mr> ...

  • Page 106

    ptg6964689cHApTER 3 : FoRMS : NEw ATTRIBuTES89on the other hand, don’t see the <datalist> element, and will instead fall back to showing what they see as a standard <select>. They also display the “If other” text and the input field that the datalist is attached to.In other word...

  • Page 107

    ptg6964689INTRoducINg HTML590The placeholder attribute A usability trick employed regularly by developers is placing text in an input field as a hint for the user, removing the text when the user focuses on the field, and restoring the text when focus leaves the field. This used to require JavaSc...

  • Page 108

    ptg6964689cHApTER 3 : FoRMS : NEw ATTRIBuTES91The pattern attributeSome of the input types mentioned previously—email, number, url, and so on—are really “baked-in” regular expressions, as the browser just checks if the values entered look like they should. Suppose you want to match agains...

  • Page 109

    ptg6964689INTRoducINg HTML592Now our regular expression has become much more compli-cated and it can be quite tricky to test this pattern on a big form in a web page. Since the pattern’s regular expression matches the syntax of a JavaScript regular expression, we can test this in a browser cons...

  • Page 110

    ptg6964689cHApTER 3 : FoRMS : NEw ATTRIBuTES93The min and max attributesAs we’ve seen with <input type=number>, these min and maxattributes constrain the range of values that can be entered in an input; you can’t submit the form with a number smaller than min or larger than max. But the...

  • Page 111

    ptg6964689INTRoducINg HTML594Consider this example:<form id=foo><input type=”text”>...</form><textarea form=foo></textarea>The <input> is owned by the form foo, as it is contained within it and does not have a form attribute overriding that ownership. The &...

  • Page 112

    ptg6964689cHApTER 3 : FoRMS : puTTINg ALL THIS TogETHER95It takes the following floating-point attributes:• value—the “measured” value shown by meter• min—the lower bound of the range for the meter• low—the point that marks the upper boundary of the “low” segment of the meter...

  • Page 113

    ptg6964689INTRoducINg HTML596<form> <label for=form-name>Name</label> <input name=form-name id=form-name type=text required> <label for=form-email>Email</label> <input name=form-email id=form-email type=email required> <label for=form-url>URL</la...

  • Page 114

    ptg6964689cHApTER 3 : FoRMS : puTTINg ALL THIS TogETHER97111We’ll echo the current value of the slider with the new outputelement.The <output> elementThe <output> element is for showing results of some calculation or other with script. It can have a form owner, either by being insid...

  • Page 115

    ptg6964689INTRoducINg HTML598During this transitional time, if you want to use HTML5 sliders, add some WAI-ARIA information, which for the time being will result in some duplication: <input id=tap name=tap type=range min=1 max=11 value=0 aria-valuemin=1 aria-valuemax=11 aria-valuenow=...

  • Page 116

    ptg6964689cHApTER 3 : FoRMS : BAckwARdS coMpATIBILITY wITH LEgAcY BRowSERS99 7,Backwards compatibility 7,with legacy browsersThe big question is: What can we do for legacy browsers? The answer is that you don’t retire your pre-existing JavaScript vali-dation or fancy DHTML datepickers just yet...

  • Page 117

    ptg6964689INTRoducINg HTML5100 7,Styling new form fields 7,and error messagesWhenever we present the new intelligent form fields at confer-ences, someone asks us how to style these new fields and error messages. You can do some basic styling on most of the new controls: fonts, colours, and the l...

  • Page 118

    ptg6964689cHApTER 3 : FoRMS : STYLINg NEw FoRM FIELdS ANd ERRoR MESSAgES101This works, but only for the currently focussed input. We want something more: we want the invalid fields to be styled differ-ently only after users have entered some content.Because of these problems, Firefox uses an alte...

  • Page 119

    ptg6964689INTRoducINg HTML5102 7,Overriding browser defaultsBuilt-in validation messages are great, but what if you want to customise these error messages? What if it’s Talk Like a Pirate Day? Perhaps I want to change all the validation messages to speak like an angry pirate, too.It’s possibl...

  • Page 120

    ptg6964689cHApTER 3 : FoRMS : oVERRIdINg BRowSER dEFAuLTS103Figure 3.13 shows a custom validation message.Unfortunately, as it stands today, only Opera supports this prop-erly. In fact, it’s questionable that the submit event should even fire if the field is invalid. Perhaps we should be listen...

  • Page 121

    ptg6964689INTRoducINg HTML5104However, if the way the custom validation messages work isn’t your bag, then there is a way to roll your own validation behav-iour, to make it feel more integral to your application. When we run setCustomValidity it sets the read-only DOM attribute called validatio...

  • Page 122

    ptg6964689cHApTER 3 : FoRMS : AVoIdINg VALIdATIoN105Element validityIndividual form fields, along with having the checkValiditymethod, also have a validity DOM attribute that returns a ValidityState object. There are a number of state attributes on the validity object, but the simplest and most ...

  • Page 123

    ptg6964689INTRoducINg HTML5106you’re selling an item). You might even want to allow your visi-tors to save the state of their submission, even if the form isn’t currently complete and valid.There are two levels of control for not validating. This can apply to the individual input control or t...

  • Page 124

    ptg6964689cHApTER 3 : FoRMS : AVoIdINg VALIdATIoN107The “whenever anything changes” eventOne almost insignificant change to the <form> element is a new event called oninput. In fact, this is a useful event that fires on the form element when any of the form fields within the form change...

  • Page 125

    ptg6964689INTRoducINg HTML5108My final colour picker makes use of the range input type, the new oninput event, and the new output elements to show the value (though this could easily use .innerHTML). The final result is shown in Figure 3.14.What’s particularly important about the oninput event ...

  • Page 126

    ptg6964689 8,CHAPTER 4 8,Video 8, and 8, 8,AudioBruce Lawson and Remy SharpA LoNg TIME Ago, in a galaxy that feels a very long way away, multimedia on the Web was limited to tinkling MIDI tunes and animated GIFs. As bandwidth got faster and compression technologies improved, MP3 music supplanted...

  • Page 127

    ptg6964689INTRoducINg HTML5110 8,Native multimedia: why, what, 8,and how?In 2007, Anne van Kesteren wrote to the Working Group:“Opera has some internal experimental builds with an imple-mentation of a <video> element. The element exposes a simple API (for the moment) much like the Audio(...

  • Page 128

    ptg6964689cHApTER 4 : VIdEo ANd AudIo : NATIVE MuLTIMEdIA: wHY, wHAT, ANd How?111This code is ugly and ungainly. Worse still is the fact that the browser has to pass the video off to a third-party plugin; hope that the user has the correct version of that plugin (or has the rights to download and...

  • Page 129

    ptg6964689INTRoducINg HTML5112What HTML5 multimedia isn’t good forRegardless of the sensationalist headlines of the tech journalists, HTML5 won’t “kill” all plugins overnight. There are use-cases for plugins not covered by the new spec.Copy protection is one area not dealt with by HTML5...

  • Page 130

    ptg6964689cHApTER 4 : VIdEo ANd AudIo : NATIVE MuLTIMEdIA: wHY, wHAT, ANd How?113Similar to <object>, you can put fallback markup between the tags for older web browsers that do not support native video. You should at least supply a link to the video so users can download it to their hard d...

  • Page 131

    ptg6964689INTRoducINg HTML5114controlsProviding controls is approximately 764 percent better than autoplaying your video. See Figure 4.2. You can use some simple JavaScript to write your own (more on that later) or you can tell the browser to provide them automatically:<video src=leverage-a-sy...

  • Page 132

    ptg6964689cHApTER 4 : VIdEo ANd AudIo : NATIVE MuLTIMEdIA: wHY, wHAT, ANd How?115posterThe poster attribute points to an image that the browser will use while the video is downloading, or until the user tells the video to play. (This attribute is not applicable to <audio>.) It removes the n...

  • Page 133

    ptg6964689INTRoducINg HTML5116loopThe loop attribute is another Boolean attribute. As you would imagine, it loops the media playback. Support is flaky at the moment, so don’t expect to be able to have a short audio sam-ple and be able to loop it seamlessly. Support will get better—browsers as...

  • Page 134

    ptg6964689cHApTER 4 : VIdEo ANd AudIo : codEcS—THE HoRRoR, THE HoRRoR117srcAs on an <img>, the src attribute points to audio or video resource, which the browser will play if it supports the specific codec/container format. Using a single source file with the srcattribute is really only u...

  • Page 135

    ptg6964689INTRoducINg HTML5118TABLE 4.1 Video codec support in modern browsers. wEBM (Vp8 codEc)Mp4 (H.264 codEc)ogV (ogg THEoRA codEc)OperaYesNoYesFirefoxYesNoYesChromeYesYes—see Note, support will be discontinuedYesIE9 +Yes (but codec must be installed manually)YesNoSafariNoYesNoMarvel at ...

  • Page 136

    ptg6964689cHApTER 4 : VIdEo ANd AudIo : codEcS—THE HoRRoR, THE HoRRoR119What’s the “best” codec?Asking what’s “better” (WebM or MP4) starts an argument that makes debating the merits of Mac or PC seem like a quiet chat between old friends.To discuss inherent characteristics, you nee...

  • Page 137

    ptg6964689INTRoducINg HTML5120Line 1 tells the browser that a video is to be inserted and gives it default controls. Line 2 offers an MP4 version of the video. We’ve put the mp4 first, because some old versions of Mobile Safari on the iPad have a bug whereby they only look at the first <sour...

  • Page 138

    ptg6964689cHApTER 4 : VIdEo ANd AudIo : codEcS—THE HoRRoR, THE HoRRoR121Remember that the contents of the <video> element can contain markup, like the text and links in the previous example? Here, we’ll place an entire Flash video player movie into the fallback content instead (and of c...

  • Page 139

    ptg6964689INTRoducINg HTML5122Encoding royalty-free video and audioIdeally, you should start the conversion from the source format itself, rather than recompressing an already compressed version which reduces the quality of the final output. If you already have a web-optimised, tightly compressed...

  • Page 140

    ptg6964689cHApTER 4 : VIdEo ANd AudIo : RoLLINg cuSToM coNTRoLS123connection. Compressing a video down to a size appropriate for a small screen can save a lot of bandwidth, making your server and—most importantly—your mobile users happy.HTML5 allows you to use the media attribute on the <s...

  • Page 141

    ptg6964689INTRoducINg HTML5124TABLE 4.3 Media Attributes, Methods, and EventsATTRIBuTESMETHodSEVENTSerror stateerrorload()canPlayType(type)play()pause()addTrack(label, kind, language) loadstartprogresssuspendaborterroremptiedstalledplaypauseloadedmetadataloadeddatawaitingplayingcanplaycanplaythro...

  • Page 142

    ptg6964689cHApTER 4 : VIdEo ANd AudIo : RoLLINg cuSToM coNTRoLS125Using JavaScript and the new media API, you have complete control over your multimedia—at its simplest, this means that you can easily create and manage your own video player con-trols. In our example, we walk you through some of...

  • Page 143

    ptg6964689INTRoducINg HTML5126Play, pause, and toggling playbackNext, we want to be able to play and pause the video from a custom control. We’ve included a button element that we’re going to bind a click handler and do the play/pause functionality from. Throughout my code examples, when I re...

  • Page 144

    ptg6964689cHApTER 4 : VIdEo ANd AudIo : RoLLINg cuSToM coNTRoLS127The problem with this logic is that we’re relying entirely on our own script to determine the state of the play/pause button. What if the user was able to pause or play the video via the native video element controls somehow (som...

  • Page 145

    ptg6964689INTRoducINg HTML5128Whenever the video is played, paused, or has reached the end, the function associated with the relevant event is now fired, making sure that our control shows the right label.Now that we’re handling playing and pausing, we want to show the user how much of the vide...

  • Page 146

    ptg6964689cHApTER 4 : VIdEo ANd AudIo : RoLLINg cuSToM coNTRoLS129The code binds to the progress event, and when it fires, it gets the percentage of video that can be played back compared to the length of the video. Note the keyword this refers to the video element, as that’s the context in whi...

  • Page 147

    ptg6964689INTRoducINg HTML5130However, sometimes this event won’t fire right away (or when you’re expecting it to). Sometimes the video suspends down-load because the browser is trying to prevent overwhelming your system. That can be a headache if you’re expecting the canplay event, which w...

  • Page 148

    ptg6964689cHApTER 4 : VIdEo ANd AudIo : RoLLINg cuSToM coNTRoLS131A race to play videoHere’s where I tell you that as much as native video and audio smells of roses, there’s a certain pong coming from somewhere. That somewhere is a problem in the implementation of the media element that creat...

  • Page 149

    ptg6964689INTRoducINg HTML5132<script>function audioloaded() { // setup the fancy-pants player}window.addEventListener(‘loadedmetadata’, function (event) { if (event.target.nodeName === ‘AUDIO’) { // set this context to the DOM node audioloaded.call(event.target); }}, true)...

  • Page 150

    ptg6964689cHApTER 4 : VIdEo ANd AudIo : RoLLINg cuSToM coNTRoLS133WORKAROUND #3: JAVASCRIPT GENERATED MEDIAAnother workaround is to insert the media using JavaScript. That way you can create the media element, attach the event handlers, and then set the source and insert it into the DOM.Remember:...

  • Page 151

    ptg6964689INTRoducINg HTML5134Our previous example can be rewritten as:<audio src=”hanson.mp3”> <p>If you can read this, you can’t enjoy the soothing ¬ sound of the Hansons.</p></audio><script>function audioloaded() { // setup the fancy-pants player}var a...

  • Page 152

    ptg6964689cHApTER 4 : VIdEo ANd AudIo : RoLLINg cuSToM coNTRoLS135Fast forward, slow motion, and reverseThe spec provides an attribute, playbackRate. By default, the assumed playbackRate is 1, meaning normal playback is at the intrinsic speed of the media file. Increasing this attribute speeds up...

  • Page 153

    ptg6964689INTRoducINg HTML5136Full-screen videoFor some time, the spec prohibited full-screen video, but it’s obviously a useful feature so WebKit did its own proprietary thing with WebkitEnterFullscreen();. WebKit implemented its API in a way that could only be triggered by the user initiating...

  • Page 154

    ptg6964689cHApTER 4 : VIdEo ANd AudIo : MuLTIMEdIA AccESSIBILITY137hold other metadata files too, such as subtitles. WebM is a con-tainer (based on the open standard Matroska Media Container format) that holds VP8 video and Ogg Vorbis audio. Currently, WebM doesn’t support subtitles, as Google ...

  • Page 155

    ptg6964689INTRoducINg HTML5138This puts the subtitle text “Luftputefartøyet mitt er fullt av ål” over the video starting at 11 seconds from the beginning, and removes it when the video reaches the 13 second mark (not 13 seconds later).No browser currently supports WebVTT or <track> bu...

  • Page 156

    ptg6964689cHApTER 4 : VIdEo ANd AudIo : SYNcHRoNISINg MEdIA TRAckS139 8,Synchronising media tracksHTML5 will allow for alternative media tracks to be included and synchronised in a single <audio> or <video> element . You might, for example, have several videos of a sporting event, eac...

  • Page 157

    ptg6964689INTRoducINg HTML5140This can be accomplished with JavaScript, or declaratively with a mediagroup attribute on the <audio> or <video> element:<div> <video src=”movie.webm” autoplay controls ¬ mediagroup=movie></video> <video src=”signing.webm...

  • Page 158

    ptg6964689cHApTER 4 : VIdEo ANd AudIo : SYNcHRoNISINg MEdIA TRAckS141} else { heading.textContent = “Native web camera streaming is not supported in ¬ this browser!”;}</script>Once you’ve done that, you can manipulate the video as you please. Rich Tibbett wrote a demo t...

  • Page 159

    ptg6964689INTRoducINg HTML5142In May 2011, Google announced WebRTC, an open technology for voice and video on the Web, based on the HTML5 specifica-tions. WebRTC uses VP8 (the video codec in WebM) and two audio codecs optimised for speech with noise and echo can-cellation, called iLBC, a narrowba...

  • Page 160

    ptg6964689 8,CHAPTER 5 8,CanvasRemy SharpIF THE VIdEo ELEMENT is the poster boy of HTML5, the canvas element is definitely the Han Solo of HTML5. It’s one of the larger parts of the HTML5 specification, and in fact the canvas API, the 2D drawing context, has been split into a separate document,...

  • Page 161

    ptg6964689INTRoducINg HTML5144If you think back to the days of the version of MS Paint that came with Windows 95, you can imagine some of the func-tionality of canvas. In fact, Paint has been replicated using the canvas element, as shown in Figure 5.1. Applications that aim to become full-fledged...

  • Page 162

    ptg6964689cHApTER 5 : cANVAS 145FIguRE 5.2 More advanced drawing applications are emerging using canvas.FIguRE 5.3 The canvas drawing demo Harmony also works, unmodified, on mobile browsers.https://freepdf-books.com

  • Page 163

    ptg6964689INTRoducINg HTML5146 8,Canvas basicsThe hello world of any canvas demo starts with putting the canvas element on your page. Initially the canvas is completely invisible and by default it is 300 pixels wide by 150 pixels high:<!DOCTYPE html><title>canvas hello world</title...

  • Page 164

    ptg6964689cHApTER 5 : cANVAS : cANVAS BASIcS147The arguments to fillRect are x, y, width, and height. The x and y coordinates start in the top left. As shown in Figure 5.4, the default colour is black. Let’s add some colour and draw an out-line around the canvas so that the canvas looks like Fi...

  • Page 165

    ptg6964689INTRoducINg HTML5148The code in the previous listing uses the 2D context object to generate a linear gradient object to which you can then apply colour stops. The arguments are the starting point of the gra-dient, x1 and y1, and the endpoint of the gradient, x2 and y2. In this example,...

  • Page 166

    ptg6964689cHApTER 5 : cANVAS : cANVAS BASIcS149 ctx.fillStyle = ctx.createPattern(this, ‘repeat’); ctx.fillRect(0, 0, canvas.width, canvas.height);};img.src = ‘remysharp_avatar.jpg’;In this example I’ve created an image on the fly using document.createElement. Only after the onload ev...

  • Page 167

    ptg6964689INTRoducINg HTML5150 8,Drawing pathsWithin the 2D API is a path API that allows you to move around the canvas and draw lines or shapes. The contrived example in Figure 5.10 shows a stick man drawn using the path API. I won’t take you through all the code used to produce the stick man,...

  • Page 168

    ptg6964689cHApTER 5 : cANVAS : dRAwINg pATHS151Once the head is drawn, I want to draw a face. The eyes and smile will be in red (well, grey in the figure). When I draw the facial features, I need to use beginPath again. Figure 5.11shows what the result would be if I didn’t use beginPath. This ...

  • Page 169

    ptg6964689INTRoducINg HTML5152There are other path methods, which are beyond the scope of this chapter, that you can use for finer control over the lines and shapes you draw, including quadraticCurveTo, bezierCurveTo, arcTo, rect, clip, and isPointInPath.When to use Canvas, when to use SVGCanvas ...

  • Page 170

    ptg6964689cHApTER 5 : cANVAS : uSINg TRANSFoRMERS: pIxELS IN dISguISE153 8,Using transformers: pixels in disguiseAs well as being able to move the pen around the canvas using methods like moveTo and drawing shapes and lines, you can adjust what happens to the canvas under the pen using transforma...

  • Page 171

    ptg6964689INTRoducINg HTML5154The translate method can help me here. It moves the 0, 0 coor-dinate to a new position. Figure 5.13 shows that I’ve drawn a dot and also shows the arguments I passed to translate. Each time translate runs it sets the new coordinates to 0, 0. Note that the translate...

  • Page 172

    ptg6964689cHApTER 5 : cANVAS : cApTuRINg IMAgES155 8,Capturing imagesAs well as drawing lines and shapes, you can copy images from other sources, specifically images, videos, and other canvas elements. I’ve already shown that you can use images as the source of a createPattern fill. You can als...

  • Page 173

    ptg6964689INTRoducINg HTML5156wanted to run a repeating thumbnail of him bashing the banana across the top of my website, I could do it by drawing a cropped and scaled version of the video using the drawImage method.The components I need are:• A canvas fixed across the top of my site• A hidde...

  • Page 174

    ptg6964689cHApTER 5 : cANVAS : cApTuRINg IMAgES157Now that the video loop is in place, I can start grabbing frames from the video element. I could use the timeupdate event to draw the canvas, but I know that the effect doesn’t perform anywhere nearly as well as if I run the canvas drawing in it...

  • Page 175

    ptg6964689INTRoducINg HTML5158per second = about 67, or approximately 15 fps—equally 25fps would be 1000/25), which should be good enough for faking video playback. Once inside the setInterval, I’ll loop over the width of the canvas, incrementing by the size of the thumbnail I’m drawing to ...

  • Page 176

    ptg6964689cHApTER 5 : cANVAS : puSHINg pIxELS159 8,Pushing pixelsOne very cool feature of the canvas API is its ability to inter-rogate individual pixels, something that isn’t possible with SVG, which is vector-based, and not really aimed at pixel-level opera-tions. You can get every pixel from...

  • Page 177

    ptg6964689INTRoducINg HTML5160the canvas. In Figure 5.16, another canvas element has been dynamically injected. You can play with the demo actionURI(http://people.mozilla.com/~prouget/demos/DynamicContentInjection/play.xhtml):here: actionURI(http://people.mozilla.com/~prouget/demos/DynamicContent...

  • Page 178

    ptg6964689cHApTER 5 : cANVAS : puSHINg pIxELS161In the previous code listing, I wait until the image has loaded before trying to copy it to the canvas. I draw it into the canvas and immediately read out the pixel data to invert the image. In the for loop, I’m using i += 4, which ensures I’m i...

  • Page 179

    ptg6964689INTRoducINg HTML5162Saving to fileYou’ve made the next best thing since sliced bread? Want to save your beautiful drawing to your desktop? You want to export it in multiple formats? No problem. Canvas has you covered.The canvas element (not the 2D context) supports exporting the curre...

  • Page 180

    ptg6964689cHApTER 5 : cANVAS : ANIMATINg YouR cANVAS pAINTINgS163var ctx = document.querySelector(‘canvas’). ¬ getContext(‘2d’);ctx.fillStyle = ‘rgb(0, 0, 255)’;ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.fillStyle = ‘rgb(0, 255, 0)’;ctx.fillRect(10, 20, 50, 50);...

  • Page 181

    ptg6964689INTRoducINg HTML5164The code used for Figure 5.18 is relatively simple and breaks down as follows: 1.Initialise the canvas and objects you want to draw.2. Clear the canvas.3. Draw the ball on the canvas.To add extra spice, I rotate Bruce’s face in circles whilst he bounces around. So ...

  • Page 182

    ptg6964689cHApTER 5 : cANVAS : ANIMATINg YouR cANVAS pAINTINgS165 ball.height = 50; ball.width = 50; ballctx = ball.getContext(‘2d’); // translate to centre to rotate properly ballctx.translate(25, 25); setInterval(draw, 10);};function draw() { ctx.clearRect(0, 0, width, height);...

  • Page 183

    ptg6964689INTRoducINg HTML5166Saving and restoring drawing stateThere is a little more hope built into the 2D API: drawing state. There are two methods on the context object: save and restore, which manage the current stack of drawing states. The savemethod pushes the current state on to the stac...

  • Page 184

    ptg6964689cHApTER 5 : cANVAS : ANIMATINg YouR cANVAS pAINTINgS167Drawing text requires the string and coordinates. For example, to show you how to use translate, I used an annotated canvas (shown in Figure 5.19 and earlier in Figure 5.13). I used fillTextto annotate the new centre point of the ca...

  • Page 185

    ptg6964689INTRoducINg HTML5168Accessibility within the canvas elementOne reason that canvas is so fast on today’s optimised JITJavaScript interpreters is that it keeps no DOM: it really is just a big bunch of pixels, with no information stored about which geometric shapes, text, or images have ...

  • Page 186

    ptg6964689 8,CHAPTER 6 8,Data Storage Remy SharpdATA SToRAgE IS fundamental in nearly all applications, web or desktop. This can include storing a unique key to track page impressions, saving usernames and prefer-ences, and so on. The list is endless.Up until now, storing data in a web app requir...

  • Page 187

    ptg6964689INTRoducINg HTML5170Looking at how cookies work, they’re overly complicated. Setting a cookie in JavaScript looks like this:document.cookie = “foo=bar; path=/”;That’s a session-based cookie. Now, if I want to store something for longer, I’ll have to set it in the future, and g...

  • Page 188

    ptg6964689cHApTER 6 : dATA SToRAgE : SToRAgE opTIoNS171• IndexedDB—at the time of writing, experimental support in Chrome 12, Firefox 5, and Internet Explorer 10— actionURI(http://www.w3.org/TR/Indexeddb/):http://www.w3.org/TR/Indexeddb/Conveniently, the name Web SQL Database instantly gi...

  • Page 189

    ptg6964689INTRoducINg HTML5172All data is tied to document origins which is made up of the pro-tocol, plus host, plus port number (which defaults to port 80)—which means that data actionURI(http://remysharp.com):on actionURI(http://remysharp.com):http://remysharp.comactionURI(http://remysharp.c...

  • Page 190

    ptg6964689cHApTER 6 : dATA SToRAgE : wEB SToRAgE173Watch out for Firefox cookie securityFirefox implements slightly different security around access to session and local storage: If cookies are dis-abled, accessing sessionStorage or localStorage will throw a security error. For this reason, your...

  • Page 191

    ptg6964689INTRoducINg HTML5174An overview of the APISince both sessionStorage and localStorage descend from the Web Storage API, they have the exact same API (from the specification):readonly attribute unsigned long length;getter DOMString key(in unsigned long index);getter DOMString getItem(in D...

  • Page 192

    ptg6964689cHApTER 6 : dATA SToRAgE : wEB SToRAgE175If sessionStorage had stored the value as a number, you would see an alert box showing 17. Instead, the cost of $12 was saved as a string. Because JavaScript uses the same method for con-catenation as it does for addition (for example, the plus ...

  • Page 193

    ptg6964689INTRoducINg HTML5176Using the key methodThe API also provides the key method, which takes an index parameter and returns the associated key. This method is useful to enumerate the data stored in the storage object. For exam-ple, if you wanted to show all the keys and associated data, yo...

  • Page 194

    ptg6964689cHApTER 6 : dATA SToRAgE : wEB SToRAgE177Using clear removes all entries, clearing the entire storage object. For examplesessionStorage.setItem(‘remy’, “Master of the Universe”);sessionStorage.setItem(‘bruce’, “Master of the Puniverse”);alert( sessionStorage.length ); /...

  • Page 195

    ptg6964689INTRoducINg HTML5178As I mentioned in the API overview section, if the key doesn’t exist in the storage object, then it will return null. This isn’t a problem for the native JSON parsers as JSON.parse(null) returns null—as you would expect. However, for Douglas Crockford’s JavaS...

  • Page 196

    ptg6964689cHApTER 6 : dATA SToRAgE : wEB SToRAgE179FIREFOX’S DEBUGGERUsing Firefox’s native JavaScript console you can easily inspect the storage objects. If you enter “sessionStorage” or “localStorage” in the console command and execute the code, the storage object can now be click...

  • Page 197

    ptg6964689INTRoducINg HTML5180Storage EventsWhat makes Web Storage particularly unique is that it also comes with events that notify you of updates to the data store.The first thing to know is that the storage event doesn’t fire on the window storing the actual data. It will only fire on the ot...

  • Page 198

    ptg6964689cHApTER 6 : dATA SToRAgE : wEB SToRAgE181Now we return to the website, and whilst browsing, we decide that we’d rather listen to Katy Perry and put a swift end to the live radio stream from Smashie and Nicey. But herein lies the problem: We’ve hit Play in the main window, but the p...

  • Page 199

    ptg6964689INTRoducINg HTML5182function handleStorage(event) { event = event || window.event; // support IE8 if (event.newValue === null) { // it was removed stopPlaying(); } else { // start playing and update display startPlaying(event.newValue); }}window.addEventListener(‘storage...

  • Page 200

    ptg6964689cHApTER 6 : dATA SToRAgE : wEB SToRAgE183 getItem: function (key) { return data[key] || null; }, key: function (i) { // not perfect, but works var ctr = 0; for (var k in data) { if (ctr == i) return k else ctr++; } ...

  • Page 201

    ptg6964689INTRoducINg HTML5184 8,Web 8, SQL 8, DatabaseWeb SQL Database is another way to store and access data. As the name implies, this is a real database that you are able to query and join results. If you’re familiar with SQL, then you should take like a duck to water with the database API...

  • Page 202

    ptg6964689cHApTER 6 : dATA SToRAgE : wEB SQL dATABASE185Be wary of versioning!The implementations of Web SQL Database support a slightly older version of the Web SQL Database API, and more specifically the versioning model.Although the specification describes how you can manage and migrate from ...

  • Page 203

    ptg6964689INTRoducINg HTML5186var db;if (window.openDatabase) { db = openDatabase(‘mydb’, ‘1.0’, ‘My first database’, ¬ 2 * 1024 * 1024);}It’s as simple as that. Next you need to set up a new table in the database, which—like all other operations we’ll be doing on this databas...

  • Page 204

    ptg6964689cHApTER 6 : dATA SToRAgE : wEB SQL dATABASE187However, the next step of this application is to load the data-base with tweets from Twitter, and as this has to happen once the table is in place (because of the asynchronous nature of the Web SQL Database API), you’ll have to get the tw...

  • Page 205

    ptg6964689INTRoducINg HTML5188function setupDatabase() { db = openDatabase(‘tweets’, ‘1.0’, ‘db of tweets’, ¬ 2 * 1024 * 1024); db.transaction(function (tx) { tx.executeSql(‘CREATE TABLE tweets (id unique, ¬ screen_name, date integer, text)’); }); getTweets();}A few...

  • Page 206

    ptg6964689cHApTER 6 : dATA SToRAgE : wEB SQL dATABASE189 // div 1000 to get to seconds }); });}The INSERT statement is the most important part, and now you can see how the field arguments work:tx.executeSql(‘INSERT INTO tweets (id, screen_name, date, ¬ text) VALUES (?, ?, ?, ?)...

  • Page 207

    ptg6964689INTRoducINg HTML5190This code may initially look complicated, but there are actually only a couple of things happening here:1.Start a new transaction.2. Run a single SQL statement, whose structure is determined by whether you want “all” or not.Loop through the results constructing t...

  • Page 208

    ptg6964689cHApTER 6 : dATA SToRAgE : wEB SQL dATABASE191Here is the complete code including the database support detection and the click handler code for the radio buttons:<!DOCTYPE html><html lang=”en”><head><meta charset=utf-8 /><title>HTML5 tweet time range&l...;

  • Page 209

    ptg6964689INTRoducINg HTML5192 db.transaction(function (tx) { tx.executeSql(‘CREATE TABLE tweets (id unique, ¬ screen_name, date integer, text)’); }); getTweets();}function getTweets() { var script = document.createElement(‘script’); script.src = ‘http://search.twitter.com...

  • Page 210

    ptg6964689cHApTER 6 : dATA SToRAgE : wEB SQL dATABASE193 }); });}// bind the click handlers for the radio buttons[].forEach.call(document.querySelectorAll(‘input ¬ [type=radio]’), function (el) { el.onclick = function () { show(this.value); }});// go!setupDatabase();</script>...

  • Page 211

    ptg6964689INTRoducINg HTML5194 tx.executeSql(‘INSERT INTO foo (id, text) VALUES ¬ (1, “foobar”)’);});db.transaction(function (tx) { tx.executeSql(‘DROP TABLE foo’); // known to fail - so should rollback the DROP statement tx.executeSql(‘INSERT INTO foo (id, text) VALUES ...

  • Page 212

    ptg6964689cHApTER 6 : dATA SToRAgE : INdExEddB195 8,IndexedDBIndexedDB was being talked about when the first edition of this book was published, but there were no implementations at the time. Today there are only vendor-prefixed implementations at this point, but I suspect it won’t be long bef...

  • Page 213

    ptg6964689INTRoducINg HTML5196Creating new IndexedDBsTo kick things off you need to open a new indexed database. You’ll use the return value to create object stores and handle any errors, similar to Web SQL Database where you receive a database object and then open the database.However, with In...

  • Page 214

    ptg6964689cHApTER 6 : dATA SToRAgE : INdExEddB197 // handle version control // then create a new object store};request.onerror = function (event) { alert(‘Something failed: ‘ + event.target.message);};Notice the error handler. In IndexedDB, errors bubble up from the request up to transact...

  • Page 215

    ptg6964689INTRoducINg HTML5198 verRequest.onsuccess = function (event) { // now we’re ready to create the object store! }; verRequest.onerror = function () { console.log(‘unable to set the version :(‘); }; }};Once the success event fires we can create our new object s...

  • Page 216

    ptg6964689cHApTER 6 : dATA SToRAgE : INdExEddB199With this we have now given the index a name (the first argu-ment), and then the name of the property (in our case, ‘director’) we want indexed when new objects are stored. Finally, we’ll allow more than one film by the same director by indi...

  • Page 217

    ptg6964689INTRoducINg HTML5200This code is actually doing quite a lot on the last three lines, and if you’re like me, you might think there’s some unnecessary repetition.We’re performing three separate tasks, outlined below.1. Create the transactiontransaction = db.transaction([‘blockbust...

  • Page 218

    ptg6964689cHApTER 6 : dATA SToRAgE : INdExEddB2012. Get a reference to the storestore = transaction.objectStore(‘blockbusters’)This is where we get a hard fix on the object store we want to work with, and here we have to name the store. This could be any of the stores we listed in our transa...

  • Page 219

    ptg6964689INTRoducINg HTML5202What if you wanted to get all the videos out of the store? Using the get method won’t cut it. We need to iterate through the entire data store:var transaction = db.transaction([‘blockbusters’],READ_WRITE), store = transaction.objectStore(‘blockbusters’),...

  • Page 220

    ptg6964689cHApTER 6 : dATA SToRAgE : INdExEddB203 // value is the stored object data.push(cursor.value); } // get the next object cursor.continue(); } else { callback(data); } };}// example usagefind(function (data) { return data.rating > 5;}, functio...

  • Page 221

    ptg6964689INTRoducINg HTML5204version transaction. Remember earlier on in this section, when I showed you how to create object stores—the setVersion success handler is the only time you can both add and remove stores.Finally, there’s deleteDatabase. As handy as this would be for debugging, un...

  • Page 222

    ptg6964689cHApTER 6 : dATA SToRAgE : SuMMARY205However, it’s still early days, and as a developer, the simplicity of working with IndexedDB has a much nicer feeling than Web SQL Database—or certainly for this developer it does. 8,SummaryIn this chapter, you learned about three different APIs...

  • Page 223

    ptg6964689This page intentionally left blank https://freepdf-books.com

  • Page 224

    ptg6964689 8,CHAPTER 7 8,OfflineRemy SharpHow MANY TIMES have I been working on a train, desperately trying to get a 3G connection with my cheap dongle, and failed to navigate a web application because we went into a tunnel (and thus lost all connectivity)? A lot, that’s how many. Computing wi...

  • Page 225

    ptg6964689INTRoducINg HTML5208 8,Pulling the plug: going offlineTo work offline, an application need only a manifest telling the browser what it needs to store in its local cache. The manifest can be as simple as a list of files and you’ll be done. Once the browser has stored the cache of asset...

  • Page 226

    ptg6964689cHApTER 7 : oFFLINE : THE cAcHE MANIFEST209 8,The cache manifestThe manifest is the thing that tells the browser when and what to get from its offline cache, from the Web, or to fall back onto if assets are missing. Once the manifest is loaded or updated, it triggers an update on the ap...

  • Page 227

    ptg6964689INTRoducINg HTML5210Here’s what the contents of my time.appcache look like:CACHE MANIFESTindex.htmltime.jstime.cssFALLBACK:server-time.js fallback-server-time.jsNETWORK:*# version 8The format of the file is important. You’ll see the first line is CACHE MANIFEST. This tells the brows...

  • Page 228

    ptg6964689cHApTER 7 : oFFLINE : THE cAcHE MANIFEST211manifest and it can’t be accessed with the existing connection, then serve up the file specified on the right side, in my case fallback-server-time.js. The fallback file fallback-server-time.js is included in the files that are cached by the...

  • Page 229

    ptg6964689INTRoducINg HTML5212In addition to the CACHE and FALLBACK categories, there’s the NETWORK category, which already has entries associated with it in our example. This is the whitelist category, and what’s important about these entries is that they tell the browser that any requests t...

  • Page 230

    ptg6964689cHApTER 7 : oFFLINE : NETwoRk ANd FALLBAck IN dETAIL213Using the network whitelistThe NETWORK namespace works in a similar way to the FALLBACK namespace, in that you can specify a full URL to whitelist, or you can specify a prefix to match against.There is also a special rule that if th...

  • Page 231

    ptg6964689INTRoducINg HTML5214 8,How to serve the 8,manifestThere’s one last hurdle to jump before you can take your appli-cation completely offline: You need to serve the manifest file properly, meaning it must have the extension .appcache and it must have the right mime type.If you’re usin...

  • Page 232

    ptg6964689cHApTER 7 : oFFLINE : THE BRowSER-SERVER pRocESS215Watch out for dodgy foxes!Firefox boasts support for offline applications, but it doesn’t quite work as smoothly as other browsers, and there are a few important bugs to be aware of. If you’re testing with Firefox, make sure you’r...

  • Page 233

    ptg6964689INTRoducINg HTML52167. Browser: application cache has updated, and triggers an event stating so.Now the browser has fully loaded the cache using the files listed in the manifest. If the manifest hasn’t changed and the browser is reloaded, here’s what happens:1.Browser: actionURI(htt...

  • Page 234

    ptg6964689cHApTER 7 : oFFLINE : AppLIcATIoNcAcHE2171.Browser: actionURI(http://introducinghtml5.com/examples/ch07/time/):re-requests actionURI(http://introducinghtml5.com/examples/ch07/time/):http://introducinghtml5.com/actionURI(http://introducinghtml5.com/examples/ch07/time/):examples/ch07/time...

  • Page 235

    ptg6964689INTRoducINg HTML5218 // reload to get whiz bang version 2.0 if (confirm(“Do you want to update to the latest version ¬ of this app?”)) { // force a refresh if the user agrees window.location.reload(); }};However, what if you wanted to tell the user what had changed? Or ...

  • Page 236

    ptg6964689cHApTER 7 : oFFLINE : dEBuggINg TIpS219 8,Debugging tipsNo doubt you’re already thinking, “This sounds complicated.” It is and it isn’t. Once you’re a dab hand at offline apps, it’s easy. But how do you debug when you have your first run-in with it not working?Browser debug ...

  • Page 237

    ptg6964689INTRoducINg HTML5220Notice how in Figure 7.5 each asset is being logged and cached. These can also be seen individually in the resources panel:When I refresh jsconsole.com after the manifest is loaded, only the manifest file is requested and the application doesn’t need updating, as s...

  • Page 238

    ptg6964689cHApTER 7 : oFFLINE : uSINg THE MANIFEST To dETEcT coNNEcTIVITY221 8,Using the manifest 8,to detect connectivityPart of HTML5 includes a property on the navigator object that is supposed to tell you if the browser is online or offline, vianavigator.onLineHowever, as we’ve already see...

  • Page 239

    ptg6964689INTRoducINg HTML5222 fn(online); }; // attaching script node trigger the code to run document.body.appendChild(script);}testOnline(function (online) { if (online) { applicationCache.update(); } else { // show users an unobtrusive message that they’re ¬ disconnect...

  • Page 240

    ptg6964689cHApTER 7 : oFFLINE : SuMMARY223Safari clears the cache for everything except the particular win-dow that you have visible, so when you refresh, it’s still got the cache manifest included. This goes for the iPhone in particular.For Chrome, you can navigate to chrome://appcache-interna...

  • Page 241

    ptg6964689This page intentionally left blank https://freepdf-books.com

  • Page 242

    ptg6964689 9,CHAPTER 8 9,Drag and DropRemy SharpSo wE’VE coME to the black sheep chapter of our book: drag and drop. It’s not a black sheep in that cool way, like Darth Vader’s version of the Imperial TIE Fighter; no, sadly it’s the black sheep you want to leave alone in a field, and let ...

  • Page 243

    ptg6964689INTRoducINg HTML5226Now we’re in the position where Firefox, Safari, Chrome, and IE support this API. It’s not a good API—in fact, it’s probably the worst API—but it’s got some real-world implementations, so it’s worth understanding what it’s capable of.Throughout this c...

  • Page 244

    ptg6964689cHApTER 8 : dRAg ANd dRop : gETTINg INTo dRAg227Since there’s nothing to be done to the draggable images, you just need to hook up the drop zone, which requires the follow-ing event handlers:1.Drag over: Tells the browser this is an element that accepts drop data.2. On drop: Once some...

  • Page 245

    ptg6964689INTRoducINg HTML5228When something is dropped on the drop element, it triggers the drop event and you’re able to read the event.dataTransferobject. The default data type is Text, so you can use the getDatamethod and ask for the Text data type. In the case of an image, the text will be...

  • Page 246

    ptg6964689cHApTER 8 : dRAg ANd dRop : gETTINg INTo dRAg229return false, too. Since you’re doing the same thing, I’ve cre-ated a function to return false:function cancelEvent() { return false; }drop.ondragenter = cancelEvent;drop.ondragover = cancelEvent;Again, since you’re making it work in...

  • Page 247

    ptg6964689INTRoducINg HTML5230 9,Interoperability of dragged 9,dataBy using the setData and getData methods on the dataTransferobject, we can pass data from elements inside our applica-tion to other pages of our app, or across browser windows—as 280 Slides has prototyped, when dragging one sli...

  • Page 248

    ptg6964689cHApTER 8 : dRAg ANd dRop : INTERopERABILITY oF dRAggEd dATA231One final note about setData: It only accepts strings. This means you can’t store a “complex” JavaScript object in a content type. However, there’s an easy enough solution around this: JSON.stringify.All the latest b...

  • Page 249

    ptg6964689INTRoducINg HTML5232Having to construct the different content types on the dragstartevent makes you perform possibly unnecessary code execution. For example, if I were to allow the user to drag a canvas element to Photoshop, I would want to encode it as a Photoshop-compatible file and s...

  • Page 250

    ptg6964689cHApTER 8 : dRAg ANd dRop : AddINg cuSToM dRAg IcoNS233Native Drop zonesNo, we’re not talking about the place where local parachutists land. There’s a new dropzone attribute available in the drag-and-drop specification. This can be applied to the area that you want to drop data onto...

  • Page 251

    ptg6964689INTRoducINg HTML5234The result is a nice little bespoke drag icon that better represents the data you’re moving around (Figure 8.4). To keep things con-sistent with the madness that is the Drag and Drop specification, the coordinate system for the drag image is the inverse of what you...

  • Page 252

    ptg6964689cHApTER 8 : dRAg ANd dRop : AccESSIBILITY235As you’ve probably already guessed, no browser has imple-mented this (yet).However, you can prepare your drag-and-drop demos by including ARIA support. You will need to set ARIA attributes on dragstart to indicate that the element is being d...

  • Page 253

    ptg6964689INTRoducINg HTML5236In the previous code, you’re searching for the divs that have the draggable attribute. Then you add the ARIA support starting in the dragstart event. Once the element begins to drag, you set the aria-grabbed attribute to true, so that an assistive device can feedba...

  • Page 254

    ptg6964689 9,CHAPTER 9 9,GeolocationRemy SharpIN THE uk, when red telephone boxes were still a com-mon sight, inside each box was a printed note indicating the address you were calling from. This was so that if you had to call the police or an ambulance you knew where you were. Of course, this al...

  • Page 255

    ptg6964689INTRoducINg HTML5238The API is incredibly simple to work with, and you can easily enhance your web apps if they make use of any geo data by plugging this API into the app and saving users from having to finger or scroll all over your map to find themselves.Currently, Internet Explorer 9...

  • Page 256

    ptg6964689cHApTER 9 : gEoLocATIoN : STIckINg A pIN IN YouR uSER239The geolocation API offers two methods for getting the geo information from your user:1.getCurrentPosition is a one-shot method for grabbing the user’s current location.2. watchPosition keeps an eye on the user’s position and k...

  • Page 257

    ptg6964689INTRoducINg HTML5240Mobile browsers, including Mobile Safari and Opera Mobile, prompt the user with a modal dialog each time a call is made to the API, stopping all code execution until the user responds (Figure 9.3). Mobile browsers like Firefox Mobile and WebKit on Android do not bloc...

  • Page 258

    ptg6964689cHApTER 9 : gEoLocATIoN : ApI METHodS241As I mentioned before, getCurrentPosition and watchPositionmirror each other and take the same arguments:• success handler• error handler• geolocation optionsA simple use of the geolocation API would be to just pass a success handler to the...

  • Page 259

    ptg6964689INTRoducINg HTML5242Using the coordinate data, you could easily map the user’s current position on something like a Google map:if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function ¬ (position) { var coords = position.coords; showMap(coords.latitude...

  • Page 260

    ptg6964689cHApTER 9 : gEoLocATIoN : ApI METHodS243The second grade of data inside the coordinates object is sup-ported, but by default most (currently all) desktop browsers will return null. However, if the device has something like a GPS on board, the values can be determined, at which point the...

  • Page 261

    ptg6964689INTRoducINg HTML5244var speedEl = document.getElementById(‘speed’);navigator.geolocation.watchPosition(function (geodata) { var speed = geodata.coords.speed; if (speed === null || speed === 0) { speedEl.innerHTML = “You’re standing still!”; } else { // speed is in met...

  • Page 262

    ptg6964689cHApTER 9 : gEoLocATIoN : ApI METHodS245The message property is useful for developing and debugging but wouldn’t be appropriate to show the user. It’s not because it’s some cryptic rubbish from the GPS onboard chips, but because it’s bespoke to each browser (as it’s not define...

  • Page 263

    ptg6964689INTRoducINg HTML5246The alternative error: on successWhen I once visited a page that was supposed to detect my location, whilst working from home in Brighton on the south coast of England, the map placed me dead in the centre of London. I checked under the hood using browser’s web con...

  • Page 264

    ptg6964689cHApTER 9 : gEoLocATIoN : ApI METHodS247wait before giving up and triggering the error handler. However, it won’t start counting down if it’s waiting for the user to approve the request. If it does timeout, the error code is set to 3 (TIME-OUT). Setting a zero timeout (the current d...

  • Page 265

    ptg6964689INTRoducINg HTML5248 9,SummaryIf there’s any aspect of geolocation in your application, then you’d be a fool not to include this amazingly simple API. The work is virtually zero to implement. Really the work would be in creating the user interface. What’s particularly important t...

  • Page 266

    ptg6964689 9,CHAPTER 10 9,Messaging 9,and WorkersRemy SharpwEB MESSAgINg ANd wEB woRkERS are different APIs but all have the same communication API, which is why I will discuss them together. Only the Messaging API is part of the official HTML5 spec, but both of these APIs are valuable additions...

  • Page 267

    ptg6964689INTRoducINg HTML5250Browsers are effectively single-threaded applications, in that when JavaScript is running or perhaps being parsed, the page isn’t rendering. Equally, when JavaScript is performing a long and complicated function, the whole browser can be seen to lock up. What a Web...

  • Page 268

    ptg6964689cHApTER 10 : MESSAgINg ANd woRkERS : cHIT cHAT wITH THE MESSAgINg ApI251passed in, the JavaScript will throw a syntax error—not helpful, but something to watch out for if you forget. One last tip: Remem-ber to wait for the target to finish loading. The target is still a document that ...

  • Page 269

    ptg6964689INTRoducINg HTML5252one source to another. It describes how to clone the data and how it should be treated. However, most browsers don’t support this process. In fact, most browsers simply coerce the object into a string. That sucks for you and me. It means that instead of the nicely ...

  • Page 270

    ptg6964689cHApTER 10 : MESSAgINg ANd woRkERS : THREAdINg uSINg wEB woRkERS253More worrying, though, are the much more subtle issues. Say you’ve written the latest and greatest web application that does the most amazing photo manipulation. You’re using all the l33tskills you learnt from this b...

  • Page 271

    ptg6964689INTRoducINg HTML5254At this point, you’d be forgiven for thinking that you can call methods inside the worker from your document, and that data can be returned from the worker to your document. Poppycock! No, in fact, to work with a worker, everything must be communi-cated through po...

  • Page 272

    ptg6964689cHApTER 10 : MESSAgINg ANd woRkERS : THREAdINg uSINg wEB woRkERS255However, there are a number of things you can do in a worker (according to the specification):• postMessage and listen for inbound messages via onmessage• close, to end the current worker• Set event listeners• XM...

  • Page 273

    ptg6964689INTRoducINg HTML5256canvas while your app searches for prime numbers? Perhaps a strange use case, but we have workers to come to your rescue.The main document will handle starting the worker and drawing on the canvas. The only code that’s offloaded to the worker is the prime number se...

  • Page 274

    ptg6964689cHApTER 10 : MESSAgINg ANd woRkERS : THREAdINg uSINg wEB woRkERS257Matryoshka dolls: workers inside workersIf you had a watchful eye, you would have spotted that you can also create new workers from within a worker. Currently, only Firefox and Opera support this, but it’s part of the ...

  • Page 275

    ptg6964689INTRoducINg HTML5258var pendingWorkers = 0, results = {}, workingWidth = 100;onmessage = function (event) { var imageData = JSON.parse(event.data), worker = null; pendingWorkers = getNumberOfWorkers(imageData.width ¬ / workingWidth); // reset any old results results ...

  • Page 276

    ptg6964689cHApTER 10 : MESSAgINg ANd woRkERS : THREAdINg uSINg wEB woRkERS259 // perform some amazing feat of image processing var imageData = amazingImageProcess(data.imageData, ¬ data.x, data.width); postMessage(JSON.stringify({ imageData: imageData, x: data.x })); // self clos...

  • Page 277

    ptg6964689INTRoducINg HTML5260means that if you have several pop-ups or several iframes, all those documents can access this single shared worker and this single shared worker will serve all those documents.This would be useful, for example, for applications like Gmail or Facebook, where client-s...

  • Page 278

    ptg6964689cHApTER 10 : MESSAgINg ANd woRkERS : THREAdINg uSINg wEB woRkERS261In the preceding code block, you can see we’re accessing the worker via the port property. This is how you interact and, in fact, distinguish between shared and nonshared workers. As the example binds to the message ev...

  • Page 279

    ptg6964689INTRoducINg HTML5262Debugging a workerWe’ve gotten to the point in web development where the tools for debugging are so much better than ten years ago. All the lat-est browsers come with their own JavaScript debugger (though Firefox still requires Firebug as a plugin); it’s a haven ...

  • Page 280

    ptg6964689cHApTER 10 : MESSAgINg ANd woRkERS : THREAdINg uSINg wEB woRkERS263It’s great that Chrome and Safari have debugging tools, but what if you want to debug in Firefox, too? You’ll need to create your own system for posting debug messages. However, as with all communications from your w...

  • Page 281

    ptg6964689INTRoducINg HTML5264It’s also useful to be able to poke around inside a worker, some-thing I’ve found to be exceptionally useful when experimenting in JavaScript. In a nonworker environment, I can pop open my console of choice (Firebug or Dragonfly, for example) and from within ther...

  • Page 282

    ptg6964689 9,CHAPTER 11 9,Real Time Remy SharpTHE REAL-TIME wEB is one of those golden eggs of the Internet. Very cool when you come across it, but perhaps quite daunting when it comes to building it. This chapter will show you the choices of technology and how spec-tacularly simple the client-si...

  • Page 283

    ptg6964689INTRoducINg HTML5266Server-Sent Events, also known as EventSource, push messages sent in real time from the server to the browser client. These are perfect for applications that need information from a server with-out necessarily having to wait for any user interaction or input, like st...

  • Page 284

    ptg6964689cHApTER 11 : REAL TIME : wEBSockETS: woRkINg wITH STREAMINg dATA267To take something like Google Wave—the now defunct real-time web-based email and collaboration tool—as an example, if you have lots of people all in the same document, and you’re all typing, you want to send all t...

  • Page 285

    ptg6964689INTRoducINg HTML5268Creating a new WebSocket is easy and very much like creating a new Web Worker. The protocol of the URL must be ws:// but the rest of the URL can be structured just as you would a normal URL, to be:var socket = new WebSocket(‘ws://myserver.com/tweets: ¬ 8080/’);F...

  • Page 286

    ptg6964689cHApTER 11 : REAL TIME : wEBSockETS: woRkINg wITH STREAMINg dATA269socket.onmessage = function(event) { var tweetNode = renderTweet(JSON.parse(event.data)); document.getElementById(‘tweets’).appendChild(tweetNode);};Now in as many as four lines of JavaScript (excluding the rende...

  • Page 287

    ptg6964689INTRoducINg HTML5270This simple pseudo code shows you how the same techniques we used in the Message API can help with getting around the limitations of plain text. The WebSocket API really is as simple as that. All the negotiation is done out of sight by the browser for you; all the bu...

  • Page 288

    ptg6964689cHApTER 11 : REAL TIME : SERVER-SENT EVENTS271Since the browser just needs to passively receive data from the server, Server-Sent Events are a good match.Now let’s assume that while you’re carefully monitoring Bruce’s adorations on your app, you lose the connection. When you retu...

  • Page 289

    ptg6964689INTRoducINg HTML5272The server needs to keep the connection open to the client, and it must send the client a header with the mime type text/event-stream.The server needs to send new messages as such:id: 1\ndata: { “semiment”: “like”, “time”: “2011-06-23 16:43:23” ¬ }\...

  • Page 290

    ptg6964689cHApTER 11 : REAL TIME : SERVER-SENT EVENTS273 }}// finally cache the response connectionconnections.push(response);/** When a regular web request is received */connections.forEach(function (response) { history[++eventId] = { agent: ¬ request.headers[‘user-agent’], time: +new...

  • Page 291

    ptg6964689INTRoducINg HTML5274loading and then wrapping your EventSource initialisation code in a setTimeout(init, 10) helps to avoid that unsightly and nasty throbber. 9,SummaryThis chapter has equipped you with the very best in buzzword compliancy: real time. At the same time, adding a real-ti...

  • Page 292

    ptg6964689 9,CHAPTER 12 9,Polyfilling: 9,Patching 9,Old Browsers 9,to Support 9,HTML5 Today 9,Bruce Lawson and 9,Remy SharpSo, THANk You for reading this far. By now we’ve prob-ably whetted your appetite with new structural elements, piqued your interest with the new APIs, and you’re cha...

  • Page 293

    ptg6964689INTRoducINg HTML5276 9,Introducing polyfillsWhen you decorate your house, you find cracks or holes in walls and wooden surfaces that need to be filled so that the surface is level. To achieve this, you use a white filler paste that gives you a smooth, level surface upon which you can p...

  • Page 294

    ptg6964689cHApTER 12 : poLYFILLINg: pATcHINg oLd BRowSERS To SuppoRT HTML5 TodAY : FEATuRE dETEcTIoN277What makes a polyfill different from the techniques we have already, like a shim, is this: if you removed the polyfill script, your code would continue to work, without any changes required in s...

  • Page 295

    ptg6964689INTRoducINg HTML5278 9,Detecting propertiesFor example, along with the document.body shortcut property, in HTML5 we now have document.head. Not so exciting, but still useful when you want to inject some script element, for instance. As this is simply a property, it’s easy to test for ...

  • Page 296

    ptg6964689cHApTER 12 : poLYFILLINg: pATcHINg oLd BRowSERS To SuppoRT HTML5 TodAY : dETEcTINg pRopERTIES279Detecting new functionsIf you don’t know already, in JavaScript, everything is an object (and there are lots of great books dedicated to this particular aspect of JavaScript). Since we’re...

  • Page 297

    ptg6964689INTRoducINg HTML5280just for the curious, it’s worth popping the hood on Modernizr as it’s a great way to learn how some features can be detected. You might find that some places are ugly to look at as browsers sometimes lie about their support or don’t completely follow the spec...

  • Page 298

    ptg6964689cHApTER 12 : poLYFILLINg: pATcHINg oLd BRowSERS To SuppoRT HTML5 TodAY : wHERE To FINd poLYFILLS281 9,The undetectablesAs we’ve already alluded to, there are definitely nuances in writ-ing a polyfill for one technology to the next. However, there are also the black holes, those undete...

  • Page 299

    ptg6964689INTRoducINg HTML5282polyfills that provide all sorts of solutions ranging from canvas, SVG, Web Forms, WebSockets, EventSource, details element, data-* attributes, and many, many more. In addition, this resource doesn’t just include polyfills, but shims and other useful libraries as w...

  • Page 300

    ptg6964689cHApTER 12 : poLYFILLINg: pATcHINg oLd BRowSERS To SuppoRT HTML5 TodAY : A woRkINg ExAMpLE wITH ModERNIzR283Modernizr.load({ // first tests test: function () { return !!window.JSON; }, nope: ‘json2.js’}, { // second tests test: Modernizr.sessionStorage, nope: ‘sessionSto...

  • Page 301

    ptg6964689INTRoducINg HTML5284Finally, once all tests are complete and all required polyfills are loaded, the app.js file is loaded and your application can start up properly, safe in the knowledge that even if it’s running in a dirty old browser like IE6, it can still use the latest, snazziest...

  • Page 302

    ptg6964689SuMMARY285Hopefully, you’ve been enlightened by our brief foray into the new structures and APIs that you can use. There are loads more cool but not-yet-implemented things in the spec that we haven't shown you. For example, you’ll be able to register the browser as a content handler...

  • Page 303

    ptg6964689INdEx286 9,INDEXattachEvent 268,method, 251versus addEventListener 141,event, 124attributescustom 89,data, 72–73 87,global, 70–75removed in 92,HTML5, 75–76Audacity software, 139, 122Audio Data API, 135, 118<audio> element/audio 71,, 54, 127,110, 129,112–113. See also...

  • Page 304

    ptg6964689INdEx287<body> 20,element, 3–4, 22,5, 35,18, 53,36border=... attribute, 92,75–76browsers. See legacy browsers or specific browsersbuffered attribute, 141,124<button> 71,element, 54Bynens, 295,Mathias, 278CCACHE MANIFEST namespace 227,, 210, 238,221Camen, Kroc, ...

  • Page 305

    ptg6964689INdEx288data storage (continued)persistent storage 240,, 223Web SQL Database, 187, 170– 189,172, 201, 184database 204,insertions, 187–193database 204,queries, 187–193databases, 202,opening/creating, 185–186database 203,tables, 186–187database 210,transactions, 193–194ve...

  • Page 306

    ptg6964689INdEx289<footer> 33,element, 16, 35,18–20 37,, 42,25<article> 45,element, 28<blockquote> 46,element, 29form attribute 110,, 93–94<form> element/formsattributesformvalidate 123,, 106novalidate 122,, 105–106form fieldserror 118,messages, 101overriding b...

  • Page 307

    ptg6964689INdEx290IE (Internet Explorer) (continued)canvas image 179,formats, 162controls attribute, 131,114cookies, 189,172 28,CSS, 11–12<datalist> 106,element, 89drag and drop 242,, 225–229 246,, 249,232–233elements, adding 21,missing, 4 97,forms, 80 255,geolocation, 238Index ...

  • Page 308

    ptg6964689INdEx291L<label> 71,element, 54, 110,93LAMP 288,system, 271Langridge, Stuart, 80, 63languagesbidirectional 75,text, 58“The HTML5 <ruby> element in words of one syllable or less, 80,” 63<ruby> 80,element, 63Lauke, Patrick, 117, 100LeanBack Player, 156, 139legac...

  • Page 309

    ptg6964689INdEx292eventsabort 141,, 124attachEvent versus addEventListener 141,, 124canplay 141,, 124, 147,130canplaythrough 141,, 124, 147,130durationchange 147,, 130emptied 141,, 124ended 141,, 124error 141,, 124loadeddata 141,, 124, 147,130loadedmetadata 141,, 124, 147,130–134loadstart 1...

  • Page 310

    ptg6964689INdEx293PThe Paciello Group 69,, 52Parker, Todd, et al, 70, 53paths 167,API, 150–152pattern attribute 108,, 91–92pattern 164,fills, 147–149 164,patterns, 147–150paused attribute 141,, 124pause 141,event, 124pause 140,method, 140,123–124 141,, 143,126–127persistent stor...

  • Page 311

    ptg6964689INdEx294seekable attribute 141,, 124, 145,128seeked 141,event, 124seeking attribute 141,, 124seeking 141,event, 124<select> 71,element, 54, 110,93selectivizr utility 299,, 282<s> 85,element, 68Server-Sent 287,Events, 270–274server-time.js 226,, 209–211, 233,216se...

  • Page 312

    ptg6964689INdEx295“Video for Everybody!” 138,, 121videoHeight attribute 141,, 124videoWidth attribute 141,, 124vid.ly 139,, 122Villetorte, 155,Julien, 138VL 139,C, 122VoiceOver (Apple) screen reader, 70, 53volume attribute 141,, 124VP8 135,codec, 118, 139,122, 154,137 154,, 159,142VTT Ca...

  • Page 313

    ptg6964689https://freepdf-books.com

  • Page 314

    ptg6964689You love our books and you love to share them with your colleagues and friends...why not earn some $$ doing it! If you have a website, blog or even a Facebook page, you can start earning money by putting a Peachpit link on your page. If a visitor clicks on that link and purchases somet...

Free HTML Books, HTML Book Pdf, HTML Pdf Books, HTML Pdf Books Download, HTML Pdf Books Free Download, Free HTML5 Books, HTML5 Book Pdf, HTML5 Pdf Books, HTML5 Pdf Books Download, HTML5 Pdf Books Free Download, Free ReadOnline Books, ReadOnline Book Pdf, ReadOnline Pdf Books, ReadOnline Pdf Books Download, ReadOnline Pdf Books Free Download,