Free Download PDF Books, Sams Teach Yourself HTML5 Mobile Application Development In 24 Hours

Sams Teach Yourself HTML5 Mobile Application Development In 24 Hours

HTML HTML5 Mobile ReadOnline Sams

Summary of Contents

  • Page 1

    ptg99924 ProvenOne-Hour LessonsJennifer KyminSamsTeach YourselfHTML5Mobile ApplicationDevelopmenthttp://freepdf-books.com

  • Page 2

    ptg999800 East 96th Street, Indianapolis, Indiana, 46240 USAJennifer KyrninSams Teach Yourself24inHoursHTML5 Mobile ApplicationDevelopmentactionURI(http://www.freepdf-books.com /):www.freepdf-books.com http://freepdf-books.com

  • Page 3

    ptg999Sams Teach Yourself HTML5 Mobile Application Development in 24 HoursCopyright © 2012 by Pearson Education, Inc.All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, ortransmitted by any means, electronic, mechanical, photocopying, recording, or otherw...

  • Page 4

    ptg999Contents at a GlancePreface .................................. .. ............ ... .. ............. ... ..... ... ....xivPart I: Building Web Pages and Applications with the Open Web StandardHOUR 1Improving Mobile Web Application Development with HTML5 ....... .12New HTML5 Tags and Attribut...

  • Page 5

    ptg99923Adding Location Detection with Geolocation ....... ... .. ... ...... ........38724Converting HTML5 Apps to Native Apps .. ... .. ... ............. ... .........405AppendixesAAnswers to Quizzes ........................ ... ... ......... ....... ... ...............423BHTML Elements and Attr...

  • Page 6

    ptg999Table of Contents 15,Preface 15,................................................. 15,........... 15,..... 15,.. 15,.... 15,...... 15,..... 15,..... 15,.. 15,... 15,xiv 22,Part 22, I: 22, Building 22, Web 22, Pages 22, and 22, Applications 22, with 22, the 22, Open 22, Web 22, Stan...

  • Page 7

    ptg999 67,Summary 67,............................................. 67,.................... 67,...... 67,.............. 67,... 67,.. 67,46 67,Q&A 67,................................................. 67,........ 67,... 67,.... 67,. 67,.... 67,.. 67,........ 67,..... 67,... 67,....

  • Page 8

    ptg999 126,HOUR 7: 126,Upgrading a Site to HTML5 126,105 126,Deciding When and How 126,to Upgrade from 126,HTML 4 126,..... 126,.. 126,... 126,.. 126,... 126,.............. 126,... 126,105 132,HTML5 Features that W 132,ork Right Now.. 132,... 132,.. 132,... 132,.. 132,... 132,.......

  • Page 9

    ptg999 184,HOUR 10: 184,Drawing with the HTML5 184,Canvas Element 184,163 184,Using the Canvas Element 184,........................ 184,... 184,... 184,................... 184,........ 184,........ 184,. 184,163 186,Drawing Shapes on the <Canvas> 186,Element....... 186,... 186,....

  • Page 10

    ptg999 258,Form Validation.............................. 258,................... 258,.. 258,.............. 258,...... 258,......... 258,237 262,Summary 262,....................................... 262,... 262,......... 262,.. 262,........... 262,.. 262,............. 262,..... 262,......

  • Page 11

    ptg999 311,Summary 311,............................................ 311,............. 311,........ 311,.. 311,.......... 311,...... 311,..... 311,290 311,Q&A 311,..................................................... 311,... 311,.. 311,... 311,................ 311,.. 311,.... 31...

  • Page 12

    ptg999 373,Summary 373,....................................... 373,... 373,......... 373,.. 373,........... 373,.. 373,............. 373,..... 373,.... 373,352 373,Q&A 373,............................................ 373,... 373,....... 373,... 373,... 373,.... 373,. 373,.......

  • Page 13

    ptg999 440,Options Other Than Converting to Native Apps 440,..... 440,.. 440,... 440,.. 440,... 440,........... 440,... 440,..... 440,.. 440,419 440,Summary 440,............................................ 440,............. 440,........ 440,.. 440,.......... 440,...... 440,..... 4...

  • Page 14

    ptg999 454,Hour 22, “Controlling 454,the Browser History with 454,the History API” 454,.. 454,... 454,.. 454,....... 454,433 455,Hour 23, “Adding Location Detection with 455,Geolocation” 455,.. 455,... 455,.. 455,... 455,... 455,.......... 455,. 455,434 455,Hour 24, “Conve...

  • Page 15

    ptg999 6,PrefaceThe web is changing very quickly these days. New browser versions are being released everyfew months rather than every few years, and new devices are entering the marketplace allthe time. For a web developer, staying up to date on the latest trends and technology isimportant, and ...

  • Page 16

    ptg999. Building more user-friendly forms. Creating semantic divisions with new elements, such as article, section, and navThis book covers several other specifications beyond HTML5, including:. Web Open Font Format (WOFF) web fonts. Microformats and Microdata. WebSockets. Web Workers. Files API....

  • Page 17

    ptg999xviSams Teach Yourself HTML5 Mobile Application Development in 24 HoursOrganization of This BookThis book is divided into three sections:. Part I, “Building Web Pages and Applications with the Open Web Standard,” teachesyou the basics of HTML, CSS, and JavaScript, and teaches you how to...

  • Page 18

    ptg999▼PrefacexviiYou can also use the Try It Yourself sections to help you practice what you’ve learned in thehour.Try It YourselfNearly every hour will have at least one step-by-step tutorial called “Try It Yourself” to helpyou use what you’ve learned.Q&A, Quiz, and ExercisesEvery...

  • Page 19

    ptg999xviiiSams Teach Yourself HTML5 Mobile Application Development in 24 HoursAbout the AuthorJennifer Kyrnin has been teaching HTML, XML, and web design online since 1997. She hasbuilt and maintained websites of all sizes from small, single-page brochure sites to large,million-page databased si...

  • Page 20

    ptg999Reader ServicesxixWe Want to Hear from You!As the reader of this book, you are our most important critic and commentator. We valueyour opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you...

  • Page 21

    ptg999This page intentionally left blank actionURI(http://www.freepdf-books.com /):www.freepdf-books.com actionURI(http://www.freepdf-books.com /):http://freepdf-books.com

  • Page 22

    ptg999Understanding1 6,HOUR 6,1 6,Improving Mobile Web 6,Application Development 6,with HTML5What You’ll Learn in This Hour:. How HTML has grown and changed since it was invented. Where HTML5 fits in with the other versions of HTML. What the Open Web Standard is and how it relates to HTML5. H...

  • Page 23

    ptg9992HOUR 1: Improving Mobile Web Application Development with HTML5Up until around 1993, the only browser available was a text-only browser calledLynx. Then Mosaic came out with features such as images, nested lists, and forms.Most designers these days take these things for granted, but back i...

  • Page 24

    ptg999Learning What’s Different with HTML53who has ever validated a page knows that just because a page isn’t valid doesn’tmean browsers won’t be able to display it. In fact, web browsers have no problemdisplaying technically invalid HTML.Because of these difficulties, a group of web desi...

  • Page 25

    ptg9994HOUR 1: Improving Mobile Web Application Development with HTML5A New HTML5 DoctypeHTML5 has a new streamlined doctype that is very easy to remember—<!doctype html>. Nothing else is required. It doesn’t even have to be written inall caps.Did youKnow? 6,Defining Web ApplicationsApp...

  • Page 26

    ptg999▼Using the Open Web Standard5Did youKnow?Many people think HTML5 includes more than it does. In fact, features such as theHistory API (discussed in Hour 22, “Controlling the Browser History with the HistoryAPI”), local storage (Hour 21, “Web Storage in HTML5”), and geolocation (Ho...

  • Page 27

    ptg9996HOUR 1: Improving Mobile Web Application Development with HTML5WatchOut!After you have a text editor up and running, you can begin writing your HTML, whichis defined by tags that are written inside of less-than (<) and greater-than (>) signs.1.Open your text editor and type the follo...

  • Page 28

    ptg999Writing Mobile Websites7WatchOut!Testing Is CriticalIf you plan to create pages and applications for iOS and Android devices as wellas desktop browsers, always test your documents in Internet Explorer 8. Thisbrowser (and IE 7) still has the lion’s share of the browser market, and if yourp...

  • Page 29

    ptg9998HOUR 1: Improving Mobile Web Application Development with HTML5WatchOut!What is the Screen Size and Resolution of theMobile DeviceWhen you’re working with mobile devices, obviously the screen size is going to besmaller than on a desktop. In general, with smartphones, you have to prepare ...

  • Page 30

    ptg999Writing Mobile Websites9Did youKnow?Content for mobile sites shouldn’t be limited, however. In fact, the W3C recommends“...making, as far as is reasonable, the same information and services available tousers irrespective of the device they are using.”1This doesn’t mean that you can...

  • Page 31

    ptg99910HOUR 1: Improving Mobile Web Application Development with HTML5By theWay. Graphics for layout—Like using tables for layout, adding invisible graphicsto add spaces and affect layout typically make many older mobile deviceschoke or display the page incorrectly. Plus, they add to the downl...

  • Page 32

    ptg999Summary11What Testing Does Your Mobile Site Need?Be prepared to test your site on as many mobile devices as you possibly can.Although you can use your browser to test or emulate things such as screen size, you won’t see some of the horrible things that can go wrong if you don’t test onm...

  • Page 33

    ptg99912HOUR 1: Improving Mobile Web Application Development with HTML5XHTML 1, and HTML5 as well as what web applications are and how they relate tothe Open Web Standard. You learned how to write a basic HTML web page and whyHTML5 fits in so well with mobile devices. You also learned some powerf...

  • Page 34

    ptg999Workshop13click on, where they leave, and so on). With this method, even if you can’t getdirect customer feedback you can see what features they are currently usingand adjust your site accordingly.Q.You mentioned using a content management system for maintaining amobile site. Do you have ...

  • Page 35

    ptg999This page intentionally left blank actionURI(http://www.freepdf-books.com /):www.freepdf-books.com http://freepdf-books.com

  • Page 36

    ptg999The New HTML5 Tags15 6,HOUR 6,2 6,New HTML5 Tags 6,and 6,Attributes with Mobile 6,DevelopmentWhat You’ll Learn in This Hour:. How to use the many new tags and attributes in HTML5. Other changes in HTML5. Mobile support for HTML5. Reasons to use HTML5 for mobile web applicationsHTML5 ha...

  • Page 37

    ptg999▼16HOUR 2: New HTML5 Tags and Attributes with Mobile DevelopmentThese tags are:. <article>—An independentportion of the document or site.. <aside>—Content that is tangential to the main part of the page or site.. <figcaption>—Caption for a figure.. <figure>...

  • Page 38

    ptg999The New HTML5 Tags17<title>My HTML 4 2-Column Page</title><link type=”text/css” href=”styles.css”></head><body><div id=”main”><div id=”header”><h1>My HTML 4 2-Column Page</h1></div><div id=”nav”><ul>...

  • Page 39

    ptg99918HOUR 2: New HTML5 Tags and Attributes with Mobile DevelopmentBy theWay</nav><section id=”contents”><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit,nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Utminim veniam, quis nostrud exerci ta...

  • Page 40

    ptg999The New HTML5 Tags19WatchOut!. <time>—Date or time.. <wbr>—Optional line break.One of the easiest new semantic elements to understand is the <time>element. Thistag says that anything inside it is a time or a date. Calling out times and datesenables user agents to do th...

  • Page 41

    ptg99920HOUR 2: New HTML5 Tags and Attributes with Mobile DevelopmentFIGURE 2.2A simple pagewith a<canvas>tagcreating a bigblue square onan Androidtablet.. <embed>—To add other technologies that don’t have a specific HTML5 element.. <source>—The source files for embedded s...

  • Page 42

    ptg999The New HTML5 Tags21WatchOut!// put code for browsers that don’t support canvas herealert(“This page requires an HTML5 compliant browser to rendercorrectly. Other browsers may not see anything.”)}}</script>Don’t Forget to Load Your ScriptIf you use the preceding script to add ...

  • Page 43

    ptg99922HOUR 2: New HTML5 Tags and Attributes with Mobile Development<keygen>tag you can generate public-private key pairs to keep your forms secure.And best of all, the <input>tag now has 13 new types for collecting specific data:. <input type=color>. <input type=date>. &...

  • Page 44

    ptg999The New HTML5 Tags23FIGURE 2.3On the left is aform in Safariand on the rightthe same form(zoomed in) onan iPod touch.The <bdi>tag lets you change the direction of text that is written in HTML. So if youhave a document written in English (a left-to-right directional language) and youwa...

  • Page 45

    ptg99924HOUR 2: New HTML5 Tags and Attributes with Mobile Development 6,The New HTML5 AttributesMany of the new attributes in HTML5 extend the tags they are associated with. Abunch of new event attributes enable you to associate scripts to many more actionsas they happen on your web page. Plus, y...

  • Page 46

    ptg999Changes to HTML 4 Tags and Attributes25You can use these event attributes on nearly every element in HTML5, which givesyou much flexibility in how your web applications react to events.HTML5 also adds a bunch of new global attributes that you can apply to nearlyevery HTML element. The new g...

  • Page 47

    ptg99926HOUR 2: New HTML5 Tags and Attributes with Mobile Development. <b>—Text that would normally be displayed as bold.. <i>—Text that would normally be displayed as italics.. <hr>—A paragraph-level thematic break in the text.. <s>—Content that is no longer accur...

  • Page 48

    ptg999Changes to HTML Syntax in HTML527. If you use the languageattribute on a <script>tag, it must say“javascript” (case insensitive) and cannot conflict with the typeattribute.Simply leaving out this attribute is better because it has no useful purpose.. If you use the nameattribute o...

  • Page 49

    ptg99928HOUR 2: New HTML5 Tags and Attributes with Mobile DevelopmentThe biggest change that most people will notice is the doctype. As mentioned inHour 1, “Improving Mobile Web Application Development with HTML5,” it hasbeen radically simplified. All you need to write is<!doctype html>...

  • Page 50

    ptg999Benefits of HTML5 for Mobile Web Development29 6,Benefits of HTML5 for 6,Mobile Web 6,DevelopmentRemember that HTML5 is not available for every mobile device in every mobile webbrowser. As mentioned earlier, many older devices, non-smart phones, and tabletsdon’t have good HTML5 support. ...

  • Page 51

    ptg99930HOUR 2: New HTML5 Tags and Attributes with Mobile DevelopmentCustomers Prefer Web ApplicationsIn a study done in late 2010, in nearly every category examined (except for games,music, and social media) people preferred using their mobile browser rather than aseparate app.1Although it’s t...

  • Page 52

    ptg999Workshop31Q.I want to get started using HTML5 tags right now, how can I tell whether I’mwriting them correctly if the browsers don’t support them?A.Web browser support has long been a struggle for most web developers, andHTML5 has not changed that situation. But an experimental HTML5 co...

  • Page 53

    ptg999This page intentionally left blank actionURI(http://www.freepdf-books.com /):www.freepdf-books.com http://freepdf-books.com

  • Page 54

    ptg999Quick Introduction to CSS33 6,HOUR 6,3 6,Styling Mobile Pages 6,with 6,CSS3What You’ll Learn in This Hour:. How to create a CSS style sheet. Great features for applications with CSS3. Media queries to change styles based on device attributes. How to use special meta tags for better-loo...

  • Page 55

    ptg99934HOUR 3: Styling Mobile Pages with CSS3Creating a CSS Style SheetCSS is made up of one or more selectors with style properties attached. For example,to change the text color of a paragraph you would write:p {color: red;}The selector is pand the style property (enclosed in the curly braces)...

  • Page 56

    ptg999Quick Introduction to CSS35color: red;}</style></head><body><p>The text in this paragraph would be red.</p><p>And this paragraph as well.</p></body></html>The problem with embedded styles is that, similar to inline styles, they only put ...

  • Page 57

    ptg99936HOUR 3: Styling Mobile Pages with CSS3FIGURE 3.1A sample webpage with an<h1>headlinedisplayed on anAndroid tablet.As long as your HTML file is in the same folder as your style sheet file, it will load allyour styles when your page is loaded.Changing the Fonts with CSSOne of the firs...

  • Page 58

    ptg999Quick Introduction to CSS37Did youKnow?. font-variant—Set small caps. font—A shortcut style to set any or all of the preceding styles in one lineWhile all the preceding properties are good to know, the one that you should focuson is the fontproperty. This, as mentioned, lets you style t...

  • Page 59

    ptg99938HOUR 3: Styling Mobile Pages with CSS3MarginBorderPaddingContentWidthFIGURE 3.2The CSS boxmodel.Using CSS for LayoutCSS is an invaluable tool for the layout of web pages, and your layout choices aremostly limited by your imagination. The two basic ways to use CSS for layout arefloating an...

  • Page 60

    ptg999▼Quick Introduction to CSS39To change the box model with CSS, you can use these style properties:. margin. padding. border. height. widthAfter you have defined the box model on your web page elements, you can use CSSfloats to position your elements where you want them on the page.Try It Y...

  • Page 61

    ptg99940HOUR 3: Styling Mobile Pages with CSS3WatchOut!2.Set the width on the body element with CSS in the <head>of your document:<style>body { width: 100%; }</style>3.Clearing the borders, margins, and paddings on the body tag is also a good idea.body {width: 100%;margin:0;padd...

  • Page 62

    ptg999Quick Introduction to CSS41FIGURE 3.3A simple layoutdisplayed inSafari.header { width: 100% }nav { width: 38%; float: left; }article { width: 62%; }footer { width: 100%; clear: left; }</style></head><body><header><h1>Page Title</h1></header><nav&...

  • Page 63

    ptg99942HOUR 3: Styling Mobile Pages with CSS3 6,What CSS3 Adds to 6,the PartyCSS3 is the latest version of CSS. Unlike previous versions, it is being released inmodules. Modules are available for color, selectors, backgrounds and borders, and soon. These modules are at all stages of the standar...

  • Page 64

    ptg999▼What CSS3 Adds to the Party43TABLE 3.1Border-Radius Browser ExtensionsCSS3FirefoxWebKitborder-radius-moz-border-radius-webkit-border-radiusborder-bottom-left-radius-moz-border-radius-bottomleft-webkit-border-bottom-left-radiusborder-bottom-right-radius-moz-border-radius-bottomright-webki...

  • Page 65

    ptg99944HOUR 3: Styling Mobile Pages with CSS31.Open an HTML5 document and add in a <div>with a short paragraph of textinside it:<div><p>Here is a short paragraph of text.</p></div>2.Give your <div>tag an ID so it can be styled uniquely with the CSS:<div id=...

  • Page 66

    ptg999What CSS3 Adds to the Party45FIGURE 3.4A divwithdifferent typesof rounded corners, on an iPad.Box Shadows and Text ShadowsYou can add shadows to text and boxes using the CSS3 properties text-shadowandbox-shadow. The format for these styles is:text-shadow: horizontal-offset vertical-offset b...

  • Page 67

    ptg99946HOUR 3: Styling Mobile Pages with CSS3 6,Using CSS3 on Mobile DevicesCSS3 is well supported by modern smartphones and tablets that use WeKit- andOpera-based browsers. Both Android and iOS devices support many elements ofCSS3, but older phones might have trouble with these styles.Also, mob...

  • Page 68

    ptg999Workshop47transitionproperty. If you’re worried that the properties you want to usewon’t work with some browsers or devices, you can discover compatibilitytables at the site “When can I use...” actionURI(http://caniuse.com/):(http://caniuse.com/).Q.I’ve read that Internet Explorer...

  • Page 69

    ptg999This page intentionally left blank actionURI(http://www.freepdf-books.com /):www.freepdf-books.com http://freepdf-books.com

  • Page 70

    ptg99949 7,HOUR 7,4 7,Detecting Mobile Devices 7,and HTML5 SupportWhat You’ll Learn in This Hour:. How to choose the browsers and features to support. What browsers support HTML5. How to detect support for HTML5. How to create fault-tolerant web applications. How CSS3 media queries enhance de...

  • Page 71

    ptg99950HOUR 4: Detecting Mobile Devices and HTML5 Support 7,Choosing What HTML5 7,Elements to UseThe problem many web designers have with using HTML5 and CSS3 is that themajority of web browsers don’t support them. By majority, I mean Internet Explorer.Internet Explorer 9 only came out in ear...

  • Page 72

    ptg999Android and iOS Support for HTML551most HTML5 support, but only 17% of the browser market. In fact, the largest marketshare in desktop markets still belongs to Internet Explorer 8, 7, and 6 with 29.6% inJuly 20111, and these versions only support at best 20% of the HTML5 features.In compari...

  • Page 73

    ptg9995 “Morgan Stanley Internet Trends.” Morgan Stanley. April 12, 2010. actionURI(www.morganstanley.com/institutional/techresearch/pdfs/Internet_Trends_041210.pdf):www.morganstanley.com/actionURI(www.morganstanley.com/institutional/techresearch/pdfs/Internet_Trends_041210.pdf):institutional...

  • Page 74

    ptg999Detecting HTML5 Functions53Before you scoff, think about it a moment. If you have decided you want to usegeolocation (Hour 24, “Converting HTML5 Apps to Native Apps”) in your web appli-cation, you can come up with a list of every browser that you know supports geo-location, and then wri...

  • Page 75

    ptg99954HOUR 4: Detecting Mobile Devices and HTML5 SupportThat Created Element Isn’t Really CreatedWhen you create an element in the DOM, you are really just creating a dummy ele-ment in your browser’s memory. You can use it for detection without it ever show-ing up on the page.You have to do...

  • Page 76

    ptg999▼Detecting HTML5 Functions55So, to check for H.264 support in the <video>tag, first you would check that thevideoelement supports the canPlayTypemethod:return !!document.createElement(‘video’).canPlayType;Then, assuming <video>is supported, you check for the H.264 codec:!!...

  • Page 77

    ptg99956HOUR 4: Detecting Mobile Devices and HTML5 Supporth264Check();document.write(“ support H.264 video.”);</script>Test this page on both iOS and Android devices (or Firefox and IE9) to see the results.Checking That an Element Retains a ValueChecking that an element retains a value ...

  • Page 78

    ptg999Detecting HTML5 Functions57Here’s the HTML to implement it:<!doctype html><html><head><title>Check for Range Input</title><script>function rangeCheck() {var i = document.createElement(“input”);i.setAttribute(“type”, “range”);if (i.type == ...

  • Page 79

    ptg99958HOUR 4: Detecting Mobile Devices and HTML5 SupportHTMLShiv Only Lets IE Recognize the TagsThe HTML5shivscript tells Internet Explorer to recognize the new HTML5 tags asHTML. It does not add functionality to the tags. So, with the script, InternetExplorer 8 will recognize that it can apply...

  • Page 80

    ptg999▼Degrading Gracefully59The solution that works the best is to detect the problem and provide a fallbackmechanism. With this solution you recognize that not all browsers or users are thesame, and you try to mitigate the problem by providing an alternative.Remember, the solution doesn’t h...

  • Page 81

    ptg99960HOUR 4: Detecting Mobile Devices and HTML5 Support 7,Using CSS3 Media 7,Queries to Detect 7,Mobile BrowsersCSS2 introduced media-dependent style sheets to allow designers to create separatestyle sheets for different types of media. For example, you could create a style sheet for. all—A...

  • Page 82

    ptg999▼Using CSS3 Media Queries to Detect Mobile Browsers61You can test your browsers against a number of media features:. Width and height of both the screen and the device. Orientation of the screen. Aspect ratio of the screen and device. Colors, including number of colors, whether monochrome...

  • Page 83

    ptg99962HOUR 4: Detecting Mobile Devices and HTML5 Support1.Write your style sheet link:<link rel=”stylesheet” href=”smartphone.css”>2.Add in the media type:media=”screen”3.Add the max-widthand max-device-widthkeywords to your link:media=”screen and (max-width: 480px), screen ...

  • Page 84

    ptg999Testing Your Applications63. color-index—Tests for the number of colors the media can display, suchas 256 color monitors. monochrome—Tests for monochrome display or the number of bits perpixel in a monochrome displayYou can use the min-and max-prefixes with all of these options for your...

  • Page 85

    ptg99964HOUR 4: Detecting Mobile Devices and HTML5 SupportFirefox or Chrome, you can install the free Web Developer extension actionURI(http://chrispederick.com/work/web-developer/):(http:/actionURI(http://chrispederick.com/work/web-developer/):/chrispederick.com/work/web-developer/) and add some...

  • Page 86

    ptg999Workshop65<canvas>tag then detecting it is pointless. But if you’re using geolocation andare not detecting for it, then you’re making a mistake. Hour 8 covers some spe-cific detection scripts you can install on your site to help detect the technologyyou want to detect.Q.I really w...

  • Page 87

    ptg99966HOUR 4: Detecting Mobile Devices and HTML5 SupportExercises1.Write down your fault tolerance plan. Be sure to include both the mini-mum your site should support and the maximum, as well as your fallbackplans for each scenario.2.After you have fallback plans, research how to test for the t...

  • Page 88

    ptg999What What What67 7,HOUR 7,5 7,JavaScript and HTML5 7,Web 7, Application 7,sWhat You’ll Learn in This Hour:. What JavaScript is and how to install scripts. How to create a rollover on text and images. Dynamic form validation with jQuery. How easy using jQuery Mobile is to create mobile ...

  • Page 89

    ptg999▼68HOUR 5: JavaScript and HTML5 Web ApplicationsTo add JavaScript to a web page, you use the <script>tag. You can place scripts inthe <head>or in the <body>of your document. You also can trigger script functionsin any event attribute, such as onmouseoveror onload.Try It ...

  • Page 90

    ptg999What is JavaScript?69<head><title>Simple JavaScript</title><script>function hello() {alert(“Hello World”);}</script></head><body><a href=”#” onclick=”hello();”>Click Me</a><noscript><p>Hello World<p>This tex...

  • Page 91

    ptg999▼70HOUR 5: JavaScript and HTML5 Web ApplicationsWatchOut!Did youKnow?This creates a link that is blue, and when the mouse hovers over it, the link turnspurple.Rollovers and Mobile Don’t MixNever use rollovers for critical functionality in your applications, especially if youplan on attr...

  • Page 92

    ptg999What is JavaScript?714.Add the JavaScript in the onmouseoverand onmouseoutstates of the para-graph to turn on and off the pop-up text:<p onmouseover=’document.getElementById(“popup”).style.display=”inline”’onmouseout=’document.getElementById(“popup”).style.display=”no...

  • Page 93

    ptg99972HOUR 5: JavaScript and HTML5 Web ApplicationsCookies are saved as name=value pairs, and they have an expiration date and apath on your server that they can be read from. Following is an example of how youwould write a cookie with JavaScript:document.cookie = ‘name=value; expires=Day, dd...

  • Page 94

    ptg999▼What is jQuery?73By theWayis that getting a project planned, designed, and built when you’re writing JavaScriptfrom scratch takes a lot of time.In fact, most developers tend to look for pre-written scripts that they can modify fortheir needs rather than writing them from scratch.But yo...

  • Page 95

    ptg99974HOUR 5: JavaScript and HTML5 Web ApplicationsFIGURE 5.1A simple alertmessage on anAndroid Tablet.4.jQuery uses the DOM extensively, so you need to make sure that the DOM isready to be manipulated. The following code is called the document-ready handler. Add this to a new script below your...

  • Page 96

    ptg999What is jQuery?75WatchOut!$(document).ready(function(){$(“a”).click(function(event){alert(“Hello World”);});});</script></head><body><a href=”#”>Click Me</a></body></html>With jQuery, you can do all the same things you can do with JavaSc...

  • Page 97

    ptg999▼76HOUR 5: JavaScript and HTML5 Web Applications$(“#link1 img”).hover(function() {this.src = this.src.replace(“_off”,”_on”);},function() {this.src = this.src.replace(“_on”,”_off”);});});</script></head><body><a id=”link1” href=”#”><im...

  • Page 98

    ptg999What is jQuery?77Notice that all three input fields have a <span>next to them. Although thename and email fields have text, the textareadoes not. This is a tag that givesus a place to add error codes when needed.2.Write your CSS to style the form fields, information labels, and an err...

  • Page 99

    ptg99978HOUR 5: JavaScript and HTML5 Web ApplicationsFIGURE 5.2Validating aform with jQueryon an iPad.6.Call the name field validation when users leave the form field or tab out of it:name.blur(requiredName);name.keyup(requiredName);7.Repeat steps 4 through 6 for the email and message fields in t...

  • Page 100

    ptg999Using jQuery Mobile79Learning jQuery is a good idea for web application developers for a number of rea-sons, including the following:. jQuery condenses the JavaScript—Approximately five lines of jQuery isequivalent to five times that much JavaScript, but web applications, espe-cially mobi...

  • Page 101

    ptg99980HOUR 5: JavaScript and HTML5 Web ApplicationsBy theWayHere is a sample HTML document using jQuery Mobile:<!DOCTYPE html><html><head><title>Page Title</title><link rel=”stylesheet”➥href=”http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.mi...

  • Page 102

    ptg999Using jQuery Mobile81FIGURE 5.3A standardjQuery Mobilepage on aniPod touch.What’s nice is you can add all your pages into one document (if you want) andjQuery Mobile will display them correctly. For example, you could add a secondpage section with an ID id=”page2”to the preceding HTML...

  • Page 103

    ptg99982HOUR 5: JavaScript and HTML5 Web Applications 7,SummaryThis hour provided an overview of the behavior of web pages. JavaScript controls thebehaviors, and you can use it to make things happen on your web pages. Some ofthe common things people script on web pages include:. Creating rollover...

  • Page 104

    ptg999Workshop83Q.I don’t like the styles that come with jQuery Mobile—is there any way tochange the styles?A.Several themes are pre-built into jQuery Mobile that you can use to change thecolors of your applications, or you can adjust the styles yourself. Plans are alsoin place for a theme ro...

  • Page 105

    ptg999This page intentionally left blank actionURI(http://www.freepdf-books.com /):www.freepdf-books.com http://freepdf-books.com

  • Page 106

    ptg999Building a Site that Works on All Devices85 7,HOUR 7,6 7,Building a Mobile We 7,b 7,ApplicationWhat You’ll Learn in This Hour:. How to create a website or web application that is mobile friendly. How to plan a new mobile web application. How to put your plan into practice with HTML and ...

  • Page 107

    ptg99986HOUR 6: Building a Mobile Web Applicationweb.”1 Instead of designing just for desktop browsers or just for smartphones or justfor tablets, try to design applications and sites that keep all these devices in mind.To do this you should:. Make sure that the content displayed to mobile devi...

  • Page 108

    ptg999▼Deciding on What Type of Application You Want87Try It YourselfCreating an Application PlanAnswer the following questions to come up with an application plan. Writing downyour answers is best so that you can refer to your plan later.1.What is the purpose of this web application?This is th...

  • Page 109

    ptg99988HOUR 6: Building a Mobile Web Applicationsupported, and if so, is there enough money in advertising to make the applica-tion profitable?Don’t forget to take into account things such as your knowledge of program-ming or design and availability of contractors to help. Even the weather cou...

  • Page 110

    ptg999▼Building the Application in HTML89 7,Building the Application in HTMLAfter you have a basic plan of the functionality and how you want it to look, youcan start building the layout. I like to build the smartphone layout first because it isusually one column and straightforward HTML.Try It...

  • Page 111

    ptg99990HOUR 6: Building a Mobile Web Application<label for=”password”>Password:</label><br><input type=”password” name=”password” size=”12”><br><input type=”submit” value=”Login”></form><p><a>Lost password</a> &l...

  • Page 112

    ptg999Using CSS to Make the HTML Look Good91...</form></section>4.Finally, create a section where the user can complete the puzzle:<section id=”solve-puzzle”><h2>Solve a Puzzle</h2><h3>Puzzle Name</h3><p class=”question”>Q: This is the puzzl...

  • Page 113

    ptg99992HOUR 6: Building a Mobile Web ApplicationWatchOut!measurement. You should use a measurement that is relative to the browser: eitherems or percentages.An em, in HTML documents, is equal to the current default font size. So, minus anystyling, 1 em would be 16px. But this font size is pretty...

  • Page 114

    ptg999Using CSS to Make the HTML Look Good93WatchOut!sizes. But these days most people have fairly high resolution monitors that canclearly display both serif and sans serif fonts without a lot of trouble.You should limit your page to no more than two or three different typefaces. Forbody text an...

  • Page 115

    ptg99994HOUR 6: Building a Mobile Web ApplicationYou can change the color of your fonts with the colorproperty, like this:color: #000000;If you want to change the color of a background, you use the background-colorproperty, like this:background-color: #3c6ac4;CSS also lets you set background imag...

  • Page 116

    ptg999▼Using CSS to Make the HTML Look Good95Did youKnow?FIGURE 6.2The sameHTML page ona smartphone,an iPod touch,and an Androidtablet.Don’t Repeat CSS that Remains the Same in All DevicesWhen you use CSS3 media queries, you can leave out styles that will remain thesame across different devic...

  • Page 117

    ptg99996HOUR 6: Building a Mobile Web ApplicationOne thing you may notice: If you test it right now in a device such as aniPhone or Nexus, you will see the full version of the site, not the smart-phone version. This is because these devices have actual dots per inch (DPI)of more than 480 pixels w...

  • Page 118

    ptg999Adding Mobile Meta Tags for More Effective HTML5 Pages97FIGURE 6.3The two-columnlayout on aniPod touch.. apple-mobile-web-app-status-bar-style—If your application is infull-screen mode, then you can change the status bar on iOS devices to“black” or “black-translucent.”. format-det...

  • Page 119

    ptg99998HOUR 6: Building a Mobile Web ApplicationWatchOut!. apple-touch-iconand apple-touch-icon-precomposed—This alsoisn’t a meta tag. But if you add <link rel=”apple-touch-icon”href=”/icon.png”>to your document, you can specify an icon that will beused to save your application...

  • Page 120

    ptg999Optimizing Your Site for Mobile99WatchOut!Be Careful When You Disallow User ScalingAlthough you can do things with the viewport user-scalableproperty such asturn off the ability of users to zoom in and out, this can affect whether your userscan even see all the content. If the content is hi...

  • Page 121

    ptg999100HOUR 6: Building a Mobile Web ApplicationWatchOut!Did youKnow?. Remember user preference—After you know that users like viewing thefull version of your site on their iPad or Xoom, then you should use cookiesto always show them that version, with, of course, the option to switch backif ...

  • Page 122

    ptg999Optimizing Your Site for Mobile101FIGURE 6.4Click-to-talk linkon an iPhone.. Use colors that are readable—Good contrast between the foreground andbackground is important to make sure that your site is readable on smallscreens.. Do not use pixel measurements—Pixels and absolute measureme...

  • Page 123

    ptg999102HOUR 6: Building a Mobile Web Application. Avoid technology that is known to break on mobile devices—Thisincludes pop-up windows, nested tables, tables for layout, graphics forspacing and layout, frames, and image maps.Many of the best practices for building mobile web applications are...

  • Page 124

    ptg999Workshop103Q.I noticed that your HTML did not have a lot of support for IE 8 and lower, butI need to support those browsers. What can I do?A.The best way to support IE 8 and lower is to surround your HTML5 tags with<div>tags with IDs on them. For example, the HTML provided in this hou...

  • Page 125

    ptg999104HOUR 6: Building a Mobile Web ApplicationExercises1.Write a plan for a web application or website based on the informationyou read in this hour.2.Check out the HTML source code for the application you started in thishour. You can see the working application, with all the features discuss...

  • Page 126

    ptg999Deciding When and How to Upgrade from HTML105 8,HOUR 8,7 8,Upgrading a Site to HTML5What You’ll Learn in This Hour:. Facts about HTML 4 and the browsers you think support it. How to make the jump to HTML5—it’s not as hard as you think. How to evaluate the browsers that currently vis...

  • Page 127

    ptg999106HOUR 7: Upgrading a Site to HTML5But before you start thinking about staying with HTML 4 for the long term, youshould consider a few things:. HTML 4 support in web browsers isn’t nearly as widespread as you mightthink. In fact, some of the most popular browsers in use today don’t fol...

  • Page 128

    ptg999Deciding When and How to Upgrade from HTML 4107By theWayStandards add 100px to the left marginContainer elementFloated element100pxInternet Explorer Doubles that to 200pxContainer elementFloated element200pxFIGURE 7.1A representa-tion of a well-known IE 6 bugwhere marginsare doubled.In many...

  • Page 129

    ptg999108HOUR 7: Upgrading a Site to HTML5Other popular browsers include Firefox, Chrome, and Safari. Popular mobilebrowsers are Opera, Android, and iOS Safari. Mobile browsers are not as far along intheir support of HTML5, but they have better support than IE 6, 7, or 8.On desktop browsers, Fire...

  • Page 130

    ptg999Deciding When and How to Upgrade from HTML 4109When making gradual changes, start with your least popular pages, the ones thatget the fewest page views. That way, if a huge problem occurs with the changes youmake, it won’t affect as many people and you can more easily fix the problem.To a...

  • Page 131

    ptg999▼110HOUR 7: Upgrading a Site to HTML5After you have an idea of the 10 most popular desktop and mobile browsers that arecurrently used to visit your site, you can then start thinking about what HTML5 fea-tures you want to add to your site.Try It YourselfViewing Users’ Browsers in Google ...

  • Page 132

    ptg999HTML5 Features that Work Right Now111HTML5 is well positioned to support mobile devices. iOS and Android devices aregrowing in popularity, and as they do, it’s going to become more apparent that appli-cations based on standards that work on both are more cost effective. HTML5, as astandar...

  • Page 133

    ptg999112HOUR 7: Upgrading a Site to HTML5support them will give extra functionality. Hour 13, “HTML5 Forms,” dis-cusses this topic more.6.Use the <video>and <audio>tags for video and audio and include fallbackoptions for older browsers. Hour 12, “Audio and Video in HTML5,” di...

  • Page 134

    ptg999Adding HTML5 Features as Extras on Your Site113HTML5 also has a number of things that, though they aren’t supported by IE 8, theyare supported in IE 9:. Canvas—IE 9, as well as all the other browsers, can display canvas tags. Infact the only browser that doesn’t support it is Opera Mi...

  • Page 135

    ptg999114HOUR 7: Upgrading a Site to HTML5By theWayHere are some HTML5 elements you can add to your pages right now:. figureand figcaption—These tags allow you to define sections of yourdocuments as self-contained content blocks.. mark—With the mark tag you can highlight a block of text for r...

  • Page 136

    ptg999HTML5 Features that Turn Your Site into a Killer Mobile Application115. Set autofocus. Autofocus puts the cursor right inside the first form element.You are probably already doing this with JavaScript, so adding theautofocusattribute won’t hurt anything.. Check out local storage options. ...

  • Page 137

    ptg999116HOUR 7: Upgrading a Site to HTML5. Canvas—The canvas tag is a great way to add animation, games, andimages to mobile applications. You’ll learn how to use the <canvas>tag inHour 10.. Video and audio tags—Both these tags are well supported by bothAndroid and iOS and these tags...

  • Page 138

    ptg999Q&A117Q.I hate the idea of losing any customers. Isn’t there any way I can use HTML5and not drive them away?A.You should never try to drive a customer away. Remember that many of thenew features of HTML5 don’t make your site unusable for less supportingbrowsers; they just don’t ge...

  • Page 139

    ptg999118HOUR 7: Upgrading a Site to HTML5 8,WorkshopThe workshop contains quiz questions to help you process what you’ve learned inthis chapter. Try to answer all the questions before you read the answers. SeeAppendix A, “Answers to Quizzes,” for answers.Quiz1.How has Internet Explorer hel...

  • Page 140

    ptg999119 8,HOUR 8,8 8,Converting Web Apps to 8,MobileWhat You’ll Learn in This Hour:. How to make mobile design as easy as possible. What tools can help you build your mobile applications. How to find images and designs that look mobile. The tools available for testing without your purchasin...

  • Page 141

    ptg999120HOUR 8: Converting Web Apps to Mobile 8,Choosing a Web EditorYour web editor is the most important tool you can use for developing mobile webapplications. Although creating a web application using just a text editor such asNotepad is possible, a professional web editor or integrated deve...

  • Page 142

    ptg999Testing Your Application121specifically for HTML (such as Notepad or TextEdit) then finding a new web pageeditor will make your development go faster and smoother. 8,Testing 8, Your 8, ApplicationThe first step in testing your application is to see where your application currentlystands in ...

  • Page 143

    ptg999122HOUR 8: Converting Web Apps to MobileWatchOut!FIGURE 8.1Viewing a web-site on an iPodtouch.Don’t Follow any Validator BlindlyThe W3C mobileOK Checker is a valuable tool, but you shouldn’t blindly imple-ment all the guidelines it suggests. Many of the mobile checkers and validatorswer...

  • Page 144

    ptg999Evaluating Your Content123. Page size—Keep your mobile page sizes as small as possible, so that theyload quickly. A good general rule is to keep mobile page sizes, including allimages, scripts, and CSS, under 20KB for feature phones and 30KB–50KBfor smartphones and computer browsers.. G...

  • Page 145

    ptg999124HOUR 8: Converting Web Apps to Mobile. Easy to use—Pressing the Back button on a feature phone is much easierthan filling in a form. You want to keep your mobile content, especially forvery small devices, as easy and functional as possible.. What the customer wants—The smaller the de...

  • Page 146

    ptg999Changing the Visual Design for Mobile125By theWayUsing Elements of Design to Create Great MobileApplicationsYou first must learn the elements of design:. Color. Direction. Lines. Shapes. TextureObviously, color refers to those colors used on a web page. Color is also present inblack and whi...

  • Page 147

    ptg999126HOUR 8: Converting Web Apps to MobileFIGURE 8.2A simple head-line style on aniPod touch.Did youKnow?Most designers design typically in portrait mode, which for most smartphones, worksgreat. But remember that tablets are often easier to read in landscape mode. Be sureto check how your pag...

  • Page 148

    ptg999Changing the Visual Design for Mobile127Lines are another design element that are often used extensively in mobile design.You can use the <hr>tag to add horizontal lines. You can also use lines to add bor-ders around elements.As you can see in Figure 8.3 lines can help break up text, ...

  • Page 149

    ptg999▼128HOUR 8: Converting Web Apps to MobileTry It YourselfTurning a Square DIV into a CircleOne of the most annoying parts of web design is how boxy everything is. But CSS3 isstarting to change that. You can turn a <div>that would normally be square into acircle.1.Add a <div>to ...

  • Page 150

    ptg999Changing the Visual Design for Mobile129FIGURE 8.4A stripe patternthat imitatestexture.Texture can be one of the most difficult design elements for a web designer to masterbecause texture is something you feel, and web pages are seen, but not felt. Texturein a web design is the feeling of v...

  • Page 151

    ptg999130HOUR 8: Converting Web Apps to Mobile. Menus—Menus can be as complex as you like on mobile, but the mostcommon patterns for menus are of a single column of items (usually onlyone to two words long) that expands to a second level when clicked on.. Paging—Because most sites split mobil...

  • Page 152

    ptg999▼Checking for HTML5 and CSS3131By theWay▲Try It YourselfGetting Started with ModernizrThe best way to learn how to use Modernizr is to install it and try it out.1.Download the modernizr-x.x.min.jsscript actionURI(www.modernizr.com/):from www.modernizr.com/.2.Move the file to your websit...

  • Page 153

    ptg999132HOUR 8: Converting Web Apps to Mobile. Consistent rendering of HTML entities. PNG alpha transparencyOther things that may not be detectable are listed on the Modernizr wiki: actionURI(https://github.com/Modernizr/Modernizr/wiki/Undetectables):https://github.com/Modernizr/Modernizr/wiki/U...

  • Page 154

    ptg999Evaluating Finished Apps on Other Devices133WatchOut!convert HTML5 applications into native mobile apps. With PhoneGap, youcan use any of the aforementioned frameworks and then convert them intoapps you can sell on the Android and Apple app stores. If you only want toget one framework, Phon...

  • Page 155

    ptg999134HOUR 8: Converting Web Apps to MobileDesktop EmulatorsThe best emulators are the ones that run right on your desktop computer. You canget emulators for. Android actionURI(http://developer.android.com/sdk/index.html):(http://developer.android.com/sdk/index.html). iOS actionURI(https://dev...

  • Page 156

    ptg999Getting an Application to Work on Older Browsers135FIGURE 8.5Simple HTML5page in InternetExplorer 8 ignor-ing various tags.simply ignore it. The web page in Figure 8.5 is displayed with the background differ-ent in compliant browsers. But as you can see in the figure, IE 8 ignores that andd...

  • Page 157

    ptg999136HOUR 8: Converting Web Apps to Mobile<p>This is an article. If IE supported HTML5, all the text on thispage would have background color.<p>Ut enim ad minim veniam, in reprehenderit in voluptate➥consecteturadipisicing elit. Excepteur sint occaecat lorem ipsum dolor sit amet,...

  • Page 158

    ptg999Getting an Application to Work on Older Browsers137FIGURE 8.6Simple HTML5page with ascript to helpInternetExplorer 8.You can also use scripts written expressly for this purpose. Modernizr was discussedearlier in this hour, but you can use others if that script is more than you need:. HTML5S...

  • Page 159

    ptg999138HOUR 8: Converting Web Apps to Mobile<script src=”selectivizr-min.js”></script><!-- [endif] -->It doesn’t add HTML5 attributes, so you’ll need a tool like Modernizr orHTML5Shiv for that. You can get Selectivizr at actionURI(http://selectivizr.com/):http://select...

  • Page 160

    ptg999Workshop139 8,Q&AQ.You say that mobile pages should be small, with images that are also small.But what if I have an image that cannot be made any smaller?A.Most web designers work very hard on images and can get very attached tothem. But you need to remember that an image at 400 pixels ...

  • Page 161

    ptg999140HOUR 8: Converting Web Apps to MobileQuiz1.Why should you test your applications?2.How big should a mobile web page be, including all scripts, styles, andimages?3.What are the five elements of design?4.Why would you use mobile design patterns?5.How can you test a mobile application on a ...

  • Page 162

    ptg999What What What141 8,HOUR 8,9 8,Adding Meaning with 8,HTML5 8,Sectioning and Semantic 8,ElementsWhat You’ll Learn in This Hour:. How to define sections of HTML5 documents. The four primary sectioning elements. Understanding elements like <figure>and <details>. Using the many...

  • Page 163

    ptg999142HOUR 9: Adding Meaning with HTML5 Sectioning and Semantic ElementsThe four sectioning elements in HTML5 are. <article>. <aside>. <nav>. <section>Two new elements, though not explicitly sectioning elements, are sectioning roots:. <details>. <figure>A fe...

  • Page 164

    ptg999Using the New Sectioning Elements143The purpose of sectioning elements is to create outlines with headers and footers.Specifically, the outlines can be created with algorithms. Outlines are importantbecause they make the pages more accessible. Accessible user agents, such as screenreaders, ...

  • Page 165

    ptg999144HOUR 9: Adding Meaning with HTML5 Sectioning and Semantic ElementsWhere most web designers will find the most value in these new sectioning elementsis how they provide more human-readable structure to the documents. For example,when you see the <article>tag, you know that the conte...

  • Page 166

    ptg999Using the New Sectioning Elements145By theWaydefines content that is related to the article itself, such as a glossary or list of relatedarticles. If the <aside>is found outside of an <article>tag, then it defines contentthat is related to the website as a whole, but not the art...

  • Page 167

    ptg999146HOUR 9: Adding Meaning with HTML5 Sectioning and Semantic ElementsThe<nav> ElementThe <nav>element defines a section of the content that links to other pages or areasof the site. You don’t have to enclose every list of links you put on a page in a <nav>element. It is ...

  • Page 168

    ptg999Using the New Sectioning Elements147navigation section, with other navigation elements just being links within the site.Other sites might have three or four <nav>elements. For example, my site onAbout.com actionURI(http://webdesign.about.com/):(http://webdesign.about.com/) has several...

  • Page 169

    ptg999148HOUR 9: Adding Meaning with HTML5 Sectioning and Semantic ElementsAccording to the W3C, “The section element is not a generic container element.When an element is needed for styling purposes or as a convenience for scripting,authors are encouraged to use the div element instead.”1Her...

  • Page 170

    ptg999Using the New Sectioning Elements149When to Use <div>The <div>element has been the standby for designs and layout for standards-based designers for several years now, but now with HTML5, that use shouldlessen. In fact, you should really only use the <div>element when no ot...

  • Page 171

    ptg999150HOUR 9: Adding Meaning with HTML5 Sectioning and Semantic ElementsSome common figures include:. Images or groups of images. Blocks of code. Poetry or quotations. Charts and graphsWhen you are deciding whether to put content into a <figure>you need to deter-mine whether the content ...

  • Page 172

    ptg999Using the New Sectioning Elements151By theWaySuppose you group the <h1>and <h2>together in an <hgroup>:<hgroup><h1>This is a Headline</h1><h2>This is a Sub-Head</h2></hgroup><section><h1>And this is a Sub-section</h1>&l...

  • Page 173

    ptg999▼152HOUR 9: Adding Meaning with HTML5 Sectioning and Semantic ElementsIf you have contact information in your footer for the author of a post or the page,you should wrap it in the <address>element. You can then put the <address>inthe <footer>.There is a lot to learn when...

  • Page 174

    ptg999Using the New Sectioning Elements153<li><a href=””>Home</a></li><li><a href=””>About Me</a></li><li><a href=””>Photos</a></li></ul></nav></header>4.After the <header>add an <articl...

  • Page 175

    ptg999154HOUR 9: Adding Meaning with HTML5 Sectioning and Semantic Elements<h1>Recent Comments</h1><p>None</section><section><h1>Stay in Contact</h1><p><a href=””>RSS</a> or <a href=””>Newsletter</a></section>&l...

  • Page 176

    ptg999Marking Up HTML Semantically155By theWaySemantic HTML 4 ElementsA bunch of elements that are part of the HTML 4 specification are semantic:. <abbr>—AbbreviationsThe<acronym> Element Is ObsoleteThe <acronym>tag is a part of HTML 4 and defines acronyms—abbreviationsthat ...

  • Page 177

    ptg999156HOUR 9: Adding Meaning with HTML5 Sectioning and Semantic ElementsBy theWayFIGURE 9.1Searching Bingfor “HTML5mark” with theresults in bold.. <small>—This used to be text that was printed smaller than the surround-ing text, but now it represents “small print” such as legal...

  • Page 178

    ptg999Marking Up HTML Semantically157WatchOut!highlight a portion of text, that wouldn’t otherwise be highlighted. It is differentfrom the <strong>and <em>elements because <mark>adds no extra emphasis orimportance to the text, it is just highlighted.You use the <meter>el...

  • Page 179

    ptg999158HOUR 9: Adding Meaning with HTML5 Sectioning and Semantic Elements. Something being downloaded or uploaded. A computation performing. A game loadingFollowing is an example <progress> element:I am <progress max=”24” value=”12” title=”chapters”>half way</progress...

  • Page 180

    ptg999Q&A159One thing to keep in mind is that the <time>element cannot set specific datetimevalues for pre-AD dates. You also cannot encode imprecise dates such as “March2008.” To indicate dates of this nature, you need to use microformats, which Hour15, “Microformats and Microdat...

  • Page 181

    ptg999160HOUR 9: Adding Meaning with HTML5 Sectioning and Semantic ElementsQ.What if I used the <meter>element with a value outside the minimum ormaximum?A.Although the possibility exists that a future browser might display some typeof error message if you did this, the chances are very sli...

  • Page 182

    ptg999Workshop1612.Examine some existing web pages, either your own or online. See whether youcan find places where the <mark>, <meter>, <progress>, and <time>elementswould be appropriate. If you are examining your own pages, add in the ele-ments so that your pages are mor...

  • Page 183

    ptg999This page intentionally left blank actionURI(http://www.freepdf-books.com /):www.freepdf-books.com http://freepdf-books.com

  • Page 184

    ptg999How to UseHow to Use163 9,HOUR 9,10 9,Drawing with the HTML5 9,Canvas ElementWhat You’ll Learn in This Hour:. How to use the <canvas>element to draw on web pages. How to create lines, rectangles, and circles on canvases. How to use images as portions of the canvas or as patterns. ...

  • Page 185

    ptg999164HOUR 10: Drawing with the HTML5 Canvas ElementBy theWay. Dynamic graphs such as stock tickers. Photo galleries. Fancy fonts. Online visual tools such as mind maps and image editorsAnything you can draw or animate you can do in a <canvas>element. However,like every part of HTML5, yo...

  • Page 186

    ptg999Drawing Shapes on the <Canvas> Element165Did youKnow?Basic support for the <canvas>element is quite good on both iOS and Android. Infact, on mobile devices, the only one that is iffy is Opera mini.When you compare <canvas>to Flash support, you can clearly see which youshou...

  • Page 187

    ptg999▼166HOUR 10: Drawing with the HTML5 Canvas ElementYou Must Set the ContextTo draw on a <canvas>element, you must pass the string “2d” to thegetContext()method. Otherwise, your <canvas>element will not display any-thing. This way, when other contexts become available, you w...

  • Page 188

    ptg999Drawing Shapes on the <Canvas> Element167FIGURE 10.1A canvas withfour rectanglesdrawn on it.. fillRect—For drawing a filled rectangle. strokeRect—For drawing a rectangular outline. clearRect—For making an empty, transparent rectangular shapeFigure 10.1 shows these three function...

  • Page 189

    ptg999168HOUR 10: Drawing with the HTML5 Canvas ElementThe <canvas>element draws only in black and white unless you set styles. You canset the fill color and the line color with two properties:. fillStyle—The fill color. strokeStyle—The border colorYou can use color names, hexadecimal c...

  • Page 190

    ptg999Drawing Shapes on the <Canvas> Element169FIGURE 10.2Two gradientson HTMLcanvas.Radial gradients are more complicated than linear gradients because rather thandefining two points for the gradient to draw between, you are defining two imagi-nary circles. The gradient travels in all dire...

  • Page 191

    ptg999170HOUR 10: Drawing with the HTML5 Canvas ElementCircle 1Circle 2FIGURE 10.3Diagram of ahow a cone-shaped radialgradient works.To create a radial gradient like the aforementioned one in the <canvas>element,position both circles starting at the same x and y coordinates, but make the se...

  • Page 192

    ptg999Drawing Shapes on the <Canvas> Element171By theWayradGrad.addColorStop(1, “rgba(105,138,72,0)”);// draw gradient boxcontext.fillStyle = radGrad;context.fillRect(10,10, 490,490);You can see this code in action actionURI(www.html5in24hours.com/examples/canvas-circles.html):at www.ht...

  • Page 193

    ptg999▼172HOUR 10: Drawing with the HTML5 Canvas ElementTo draw a triangle, you write:context.beginPath();context.moveTo(20,30);context.lineTo(500,100);context.lineTo(250,300);context.fill();You may need to increase the size of your canvas with the width and height attrib-utes to allow this exa...

  • Page 194

    ptg999Drawing Shapes on the <Canvas> Element173FIGURE 10.4Three line capstyles: butt,square, andround.You can also adjust the width of your path lines, the shape of the end of the lines,and how these lines are joined together using the lineWidth, lineCap, lineJoin,and miterLimitproperties.T...

  • Page 195

    ptg999▼174HOUR 10: Drawing with the HTML5 Canvas ElementFIGURE 10.5Three line joinstyles: miter,bevel, andround.Try It YourselfBuilding a Line with the Three Join TypesYou can build a line with one type of join, and then swap it with the other types tosee what they look like as well. Follow the...

  • Page 196

    ptg999▼Drawing Shapes on the <Canvas> Element175By theWayLook at your canvas to see the default style of miter. Change the line joinstyle to roundand beveland look at how the corners change.The miterLimitproperty defines how sharp or dull the miter points are on a join.The higher the mite...

  • Page 197

    ptg999176HOUR 10: Drawing with the HTML5 Canvas ElementFIGURE 10.6A wave patternmade with halfcircles.1.Decide on the diameter of your circle, and define the radius as half of that:var radius = 125/2;2.Define the x and y coordinates of your first circle based on the radius:var y = radius+10;var x...

  • Page 198

    ptg999Writing Fonts and Text on the Canvas177WatchOut!You can remove the extra beginPath()and stroke()methods (all but thefirst beginPath()and last stroke()) if you are filling the circles or if youwant a line down the middle connecting them all. 9,Writing Fonts and T 9,ext on the CanvasTo draw t...

  • Page 199

    ptg999▼178HOUR 10: Drawing with the HTML5 Canvas ElementBy theWayHere is an example of how to add custom text to a <canvas>element:context.font = “bold 3em/3.5em ‘Palatino Linotype’, ‘Book Antiqua’,➥Palatino, serif”;context.textAlign = “center”;context.textBaseline = “...

  • Page 200

    ptg999Displaying Images1793.Define the blur:context.shadowBlur = 2;4.Choose a shadow color:context.shadowColor = “rgba(0,0,0,0.5)”;Having the fillTextline last in your code is important, because otherwisethe shadow and fill won’t show up. You can see an example at actionURI(www.html5in24hou...

  • Page 201

    ptg999180HOUR 10: Drawing with the HTML5 Canvas ElementFIGURE 10.7Clips used in a<canvas>element.not display on the canvas, it does not edit the image or crop it. To clip an imageyou need to indicate the coordinates, width, and height of the area to be clippedand the coordinates, width, and...

  • Page 202

    ptg999▼Displaying Images181Remember that scaling is done by the browser, and there is no quality control. Imagescan become blurry if scaled up too much and grainy if scaled down too much.Adding PatternsYou can create patterns with your images with the canvas methodcreatePattern(). You tell it w...

  • Page 203

    ptg999182HOUR 10: Drawing with the HTML5 Canvas ElementFIGURE 10.8A border patternon a canvas. 9,How Is Canvas Different from 9,SVG or Flash?The biggest difference between the <canvas>element and SVG or Flash is that<canvas>is an HTML element and as such is built right into the brows...

  • Page 204

    ptg999Summary183TABLE 10.1Different Features of Canvas, SVG, and FlashCanvasSVGFlashVector graphicsCanvas is bitmap,but can drawvectors.SVG is vectorbased, but you canload bitmaps.Flash is vectorbased.Inline HTMLCanvas is a nativeHTML element.SVG is XML andmust be embedded.Flash is SWF andmust be...

  • Page 205

    ptg999184HOUR 10: Drawing with the HTML5 Canvas ElementYou also learned how to add text and images to your canvas as well as put shadowson your drawings, add gradients to your fills, and manipulate images that are drawnon the canvas.This hour also discussed some of the differences between the <...

  • Page 206

    ptg999Workshop185on the other. Because computer monitors cannot split a pixel in half, theycompensate by anti-aliasing the pixels to either side.To fix this problem, you need to move the location of your lines to halfwaybetween the two grid marks. So, instead of drawing a 1-pixel-wide line from 3...

  • Page 207

    ptg999186HOUR 10: Drawing with the HTML5 Canvas Element5.True or False: Circles are drawn using radians as the start and end points,not degrees.6.True or False: You cannot set box model styles on canvas text.7.What two things do you need to do to draw an image file on a canvas?8.Which of these th...

  • Page 208

    ptg999Defining tDefining t187 9,HOUR 9,11 9,Fonts 9, and 9, Typography 9, in 9,HTML5What You’ll Learn in This Hour:. Changes to typography with HTML5. New CSS3 properties for fonts. How to hyphenate with CSS3. Choosing typographical entities to use. What the Web Open Font Format (WOFF) standa...

  • Page 209

    ptg999188HOUR 11: Fonts and Typography in HTML5You should consider several elements of typography when designing your pages andapplications:. Typefaces. Spacing. Hyphenation. Rag. Widows and orphansTypefacesA typeface is what most people call the “font,” but it is actually the “family.” F...

  • Page 210

    ptg999Defining the Elements of Typography189a measurement (in, cm, mm, pt, pc, em, ex, or px), or percentages. Here’san example:font-size: 80%;. line-height—Defines the distance between lines for the font. You candefine this as a number to multiply by the font size, a specific length (witha u...

  • Page 211

    ptg999▼190HOUR 11: Fonts and Typography in HTML5. font-effect—Set the text to look embossed, engraved, or outlined usingthe keywords emboss, engrave, outline, and none:font-effect: outline;. font-smooth—Apply anti-aliasing to text or turn it off. By default (auto)the text will be smoothed a...

  • Page 212

    ptg999Defining the Elements of Typography1913.Don’t forget to include a size adjustment for your fonts on your paragraph style:font-size-adjust: 0.52;}4.Define your headlines with the font size, line height, family, and weight:h1, h2, h3, h4, h5, h6 {font-family: “Palatino Linotype”, “Boo...

  • Page 213

    ptg999192HOUR 11: Fonts and Typography in HTML5FIGURE 11.1Three kerningexamples:tight, normal,and loose.The letter-spacingproperty is not exactly the same as kerning. Although puttinga spanaround every character in your document is theoretically possible, to get true,letter-perfect kerning, the r...

  • Page 214

    ptg999Defining the Elements of Typography193If you want to affect tracking with CSS, you can use the word-spacingproperty. Thisproperty adds space around words similar to how letter-spacingadds or removesspace around letters.Leading is affected with the line-heightproperty. A good general rule fo...

  • Page 215

    ptg999194HOUR 11: Fonts and Typography in HTML5FIGURE 11.2Soft hyphens injustified text.Although adding a soft hyphen inside every multi-syllable word in your document ispossible, unless you have an automatic hyphening system, this isn’t feasible for longdocuments or large sites. Instead you sh...

  • Page 216

    ptg999Defining the Elements of Typography195WatchOut!CSS3 also offers several new hyphenation style properties:. hyphens—This property controls whether hyphenation is allowed in a blockof text. The default is manual, but you can change it to none, auto, or all:hyphens: auto;. hyphenate-characte...

  • Page 217

    ptg999196HOUR 11: Fonts and Typography in HTML5By theWayAlthough there aren’t any specific tags or properties you can use to define the rag ofyour text, you can use hyphenation, font size, and even the width of your text blocksto change how the rag looks. You can even edit the text itself to us...

  • Page 218

    ptg999Using Proper Typographical Entities197TABLE 11.1Quotation Mark Type HTML EntitiesCharacterDisplayHuman-ReadableCodeNumeric CodeReplacesDouble Quotes“”&ldquo;&rdquo;&#8220;&#8221;Straight doublequotes or &quot;Single Quotes‘’&lsquo;&rsquo;&#8216;&#...

  • Page 219

    ptg999198HOUR 11: Fonts and Typography in HTML5Did youKnow?Taking the time to use the correct character entities rather than the easier-to-usealternatives may seem like a small thing to do, but by doing so you make your textclearer and easier to read. 9,Understanding Web Open Font F 9,ormat 9,(WO...

  • Page 220

    ptg999Understanding Web Open Font Format (WOFF)199The advantages to using WOFF fonts are. WOFF fonts are compressed, which means that they download more quicklycompared to raw TrueType or OpenType formats.. WOFF contains information to tell you where the font came from withoutDigital Rights Manag...

  • Page 221

    ptg999▼200HOUR 11: Fonts and Typography in HTML5Fonts Are CopyrightedThousands of fonts are out there, but most are not free. Before you upload a TTFfile to your web server, you should find out what the license is for that font. Makesure that you have permission to use the font on a web page. M...

  • Page 222

    ptg999Understanding Web Open Font Format (WOFF)201By theWay5.Include the font weight and style for clarity and close the @font-face:font-weight: normal;font-style: normal;}6.Create a style using that font family as you would any other font family:h1 {font: 3em LemonChickenRegular, Verdana, Geneva...

  • Page 223

    ptg999202HOUR 11: Fonts and Typography in HTML5Then Fontspring came up with the Fontspring @Font-Face Syntax. By adding aquestion mark in the first srcURL (for example, font.eot?#iefix), IE thenthinks the rest of the string is a URL query string and ignores it, loading just theEOT file.As you can...

  • Page 224

    ptg999Workshop203notice the difference between a straight quote and a curly quote, but they willnotice that your site is easier to read, even if only subconsciously.Besides, typography is fun!Q.You list a lot of typographic entities in this hour, but you don’t list all of them.Is there somewher...

  • Page 225

    ptg999204HOUR 11: Fonts and Typography in HTML5Exercises1.Go through an existing web page (either your own or one on the web) andfind the typographic mistakes. Look for things such as bad entities, poorspacing, too many fonts, and so on. Decide how you would correct theseproblems, and if you’re...

  • Page 226

    ptg999Why Use HTML5 for Audio and Video vs. Flash205 9,HOUR 9,12 9,Audio and Video in 9,HTML5What You’ll Learn in This Hour:. Why the <video>and <audio>tags are important. What support is available for the new multimedia elements. How to add video and audio into your HTML that w...

  • Page 227

    ptg999206HOUR 12: Audio and Video in HTML5that the browsers could open them correctly, but these HTML5 elements makeembedding video and audio much easier.A lot of discussion is going on about whether HTML5 video will “beat” Flash, andpeople are offering many reasons why it should (or should n...

  • Page 228

    ptg999Choosing Video Formats for the Best Compatibility207WatchOut!TABLE 12.1Browser Support for Video CodecsBrowserMP4/H.264ogg/TheoraWebMAndroidversion 3.0version 2.3version 2.3Chromeversion 9 (Windows)version 7 (Macintosh)version 9 (Windows)version 7 (Macintosh)version 9 (Windows)version 7 (Ma...

  • Page 229

    ptg999208HOUR 12: Audio and Video in HTML5(makers of Firefox) have stated that Firefox will never support H.264 video becauseof patent issues and their focus on open source software.However, if you want your videos to play on iPhones and iPads, you need to use thisformat, because iOS doesn’t su...

  • Page 230

    ptg999Choosing Audio Codecs for the Widest Support209TABLE 12.2Browser Support for Audio CodecsBrowsersMP3VorbisWAVAndroidversion 2.3version 2.3Chromeversion 6version 6Firefoxversion 3.6version 3.6Internet Explorerversion 9version 9iOSversion 3Operaversion 10.5version 10.5Safariversion 5version 5...

  • Page 231

    ptg999210HOUR 12: Audio and Video in HTML5WatchOut! 9,The New HTML5 Media ElementsHTML5 has several new elements you can use to add audio and video to your webpages:. <video>—Use this for a video stream.. <audio>—Use this for an audio stream.. <source>—This is the media so...

  • Page 232

    ptg999The New HTML5 Media Elements211Did youKnow?WatchOut!<audio><source src=”sound.mp3”><source src=”sound.ogg”><source src=”sound.wav”><track kind=”captions” src=”captions.srt” srclang=”en”></audio>There Is No Standard for Timed Track ...

  • Page 233

    ptg999▼212HOUR 12: Audio and Video in HTML5▲Try It YourselfAdding a Music File to Your HTMLAdding music to your web pages is easy with the <audio>element. In this exerciseyou will save your music as MP3, WAV, and Vorbis files so that it has good browsersupport.1.Record your audio file a...

  • Page 234

    ptg999Useful Attributes to Extend Your Media213WatchOut!Audio and Video AttributesSeveral attributes can be used on both <audio>and <video>elements:. autoplay—This tells the browser to start playing the song or video as soonas it has streamed enough to play without stopping. This is...

  • Page 235

    ptg999214HOUR 12: Audio and Video in HTML5Did youKnow?. heightand width—Set the height and width of the video in CSS pixels. Youcan resize your videos using these controls, but you won’t be able to changethe aspect ratio.. muted—This allows you to set the audio to mute as the default state....

  • Page 236

    ptg999Useful Attributes to Extend Your Media215The typeattribute has the following format:type=’MIME type; codecs=”video codec, audio codec”’The MIME types for MP4, Ogg, and WebM are. H.264 or MP4—video/mp4. ogg/Theora—application/ogg, video/ogg. WebM—video/webmHere is how to write ...

  • Page 237

    ptg999▼216HOUR 12: Audio and Video in HTML5 9,Creating 9,Fallback 9, Options 9, for 9, Internet 9,ExplorerThe number one reason most developers are resistant to using the new <video>and<audio>elements is because IE 8 and lower don’t support these elements. To getyour sound and mo...

  • Page 238

    ptg999Creating Custom Controls with API Methods217▲4.Add source files for the MP4, Ogg, and WebM—make sure that MP4 is first:<source src=”Shasta.mp4”><source src=”Shasta.theora.ogv”><source src=”Shasta.webm”>5.Install Flowplayer on your website (go actionURI(http...

  • Page 239

    ptg999218HOUR 12: Audio and Video in HTML5FIGURE 12.1Controls for thesame video inChrome, Safari,Firefox, and IE 9(top to bottom).But with the DOM API for video, you can write and style your own video controls.Some controls you can use are. play()—To play the media. pause()—To pause the media...

  • Page 240

    ptg999Summary219playPause.value = video.paused ? ‘Play’ : ‘Pause’;}function playPause() {if (video.paused || video.ended) {video.play();} else {video.pause();}}</script><button value=”Play/Pause” id=”playPause” onclick=”playPause()”><img src=”images/PlayPause....

  • Page 241

    ptg999220HOUR 12: Audio and Video in HTML5 9,Q&AQ.How is the <track>element intended to be used?A.This element is added to the <video>and <audio>elements to define informa-tion that is synchronized to the media. It can be a sign-language translationvideo, a text description,...

  • Page 242

    ptg999Workshop2215.What is the format for the typeattribute on the <source>element?6.How does the fallback option work on an <audio>element?Exercises1.Add an audio file to a web page. Make sure that it plays in as manybrowsers as possible.2.Choose a video player (perhaps actionURI(htt...

  • Page 243

    ptg999This page intentionally left blank actionURI(http://www.freepdf-books.com /):www.freepdf-books.com http://freepdf-books.com

  • Page 244

    ptg999New Usability Features in HTML5 Forms223 9,HOUR 9,13 9,HTML5 FormsWhat You’ll Learn in This Hour:. How to include hint text in your form fields. How to add simple attributes to make your forms easier to use. How to create lists of content for form fields. How to work with the new input ...

  • Page 245

    ptg999224HOUR 13: HTML5 FormsTwo new features that make the forms easier for users are placeholder text andautofocus. Using autocomplete combined with datalists helps make the data the formsdeliver more consistent and accurate.Placeholder TextPlaceholder text is a very useful feature in forms. It...

  • Page 246

    ptg999New Usability Features in HTML5 Forms225For browsers that don’t support the placeholderattribute, you can use JavaScriptand CSS to fake it. The easiest way is to write the placeholder text in the value ofyour input field, and then use JavaScript to hide it when the field has focus:<inp...

  • Page 247

    ptg999226HOUR 13: HTML5 Forms:-moz-placeholder {color: aliceblue;background-color: #ccc;}You can use the placeholderattribute on <input>and <textarea>elements. Itworks in Chrome 4, Firefox 3.7, iOS 4, Opera 11, and Safari 4. It does not work inAndroid or Internet Explorer.AutofocusThe...

  • Page 248

    ptg999New Usability Features in HTML5 Forms227Autocomplete and DatalistsThe autocompleteattribute and the <datalist>element are useful for both usersand web developers. Users can fill in form fields more easily when they have a picklist to start from, and developers get data that is more co...

  • Page 249

    ptg999▼228HOUR 13: HTML5 FormsTry It YourselfUsing jQuery UI as a Fallback for Autocomplete DatalistsjQuery UI has a lot of features that you can use as fallback options for HTML5forms, so it’s an important tool to know how to use. To use it follow these steps:1.Build your jQuery UI and downl...

  • Page 250

    ptg999HTML5 Input Types229FIGURE 13.3A number fieldon an AndroidGalaxy Tab10.1 (top) andin Safari(bottom).. <input type=range>. <input type=tel>The numbertype is exactly what you would think it is. However, asking for a numberin a web form is trickier than you think. For example, 17, ...

  • Page 251

    ptg999230HOUR 13: HTML5 FormsWatchOut!FIGURE 13.4A range field inSafari.Don’t Skip ValidationWhen you use the new input types, remember that in most cases, a user’s puttingin an incorrect value is still possible. If you need the values to always be consis-tent, you will need to validate the f...

  • Page 252

    ptg999HTML5 Input Types231FIGURE 13.5A telephonefield on aniPod touch.Date and Time TypesDates and times are common fields on web forms, and HTML5 provides six specificinput types to collect this information:. <input type=datetime>. <input type=datetime-local>. <input type=date>...

  • Page 253

    ptg999232HOUR 13: HTML5 FormsFIGURE 13.6A date pickerin Opera.Time is sent as:HH:MMThe datetimeand datetime-localtypes provide more specific dates, includingboth the date and the time. The only difference between the two is that the datetimeincludes time zone information and the datetime-localass...

  • Page 254

    ptg999HTML5 Input Types233FIGURE 13.7A URL field onan iPad.Email, URLs, Colors, and Search Box TypesThe four remaining types cover other standard form fields:. <input type=email>. <input type=url>. <input type=color>. <input type=search>The emailand urlfields don’t look ...

  • Page 255

    ptg999234HOUR 13: HTML5 FormsDid youKnow?FIGURE 13.8A color pickerin Opera.FIGURE 13.9A search fieldin Safari withresults (indi-cated by themagnifyingglass) andautosave.The colortype adds a color picker to browsers that support it. At this time, that isonly Opera 11. The form delivers a six-digit...

  • Page 256

    ptg999Other New Form Elements235In fact, WebKit is so strict that you cannot change some styles even with!importantrules. You can’t easily change. Padding. Font family. Font size. Border. Background colorIf you change these styles, your search box will look radically different in non-WebKit bro...

  • Page 257

    ptg999236HOUR 13: HTML5 FormsThis element is supported in all major browsers, except IE. It is quite possible thatMicrosoft never will implement <keygen>support. However, if you need to workwith secure public-private key pairs, and you don’t need to support IE, this elementis useful.Form ...

  • Page 258

    ptg999Form Validation2371 “How to Find or Validate an Email Address.” Regular-Expressions.info. Dec 2, 2010. actionURI(www.regular-expressions.info/email.html):www.regu-actionURI(www.regular-expressions.info/email.html):lar-expressions.info/email.html. Referenced May 25, 2011.You can create t...

  • Page 259

    ptg999238HOUR 13: HTML5 FormsWatchOut!FIGURE 13.10Required fieldin Chrome.The most common type of validation of forms is with required fields. To mark a fieldrequired in HTML5 you add the requiredattribute:<input type=text id=name required>Always Validate on the Server as WellLocal validati...

  • Page 260

    ptg999▼Form Validation239FIGURE 13.11Validating a pattern inFirefox.Try It YourselfCreating an HTML5 FormPutting all of these features together into a coherent and good-looking HTML5 formcan be challenging. Just because you’re using the new HTML5 features doesn’t meanyou should neglect stan...

  • Page 261

    ptg999240HOUR 13: HTML5 Forms<textarea id=description required></textarea><input type=date id=replyBy required><input type=number id=budget required>5.Add any patterns, maximums, or minimums you want to validate against:<input type=text id=phone pattern=”\([0-9]{3}\) ...

  • Page 262

    ptg999Summary241outline: none;-webkit-box-shadow: inset 0 0.2em 0.3em rgba(0,0,0,.1);-moz-box-shadow: inset 0 0.2em 0.3em rgba(0,0,0,.1);box-shadow: inset 0 0.2em 0.3em rgba(0,0,0,.1);}6.Set widths on your fields:input {width: 20em;}input[type=submit] {width: 10em;-webkit-border-radius: 0.5em;-mo...

  • Page 263

    ptg999242HOUR 13: HTML5 FormsYou learned about the 13 new input types such as email, number, and date. You alsolearned about four new elements that will give your forms more utility after theseelements are better supported.You also learned how to use the new HTML5 attributes to validate both requ...

  • Page 264

    ptg999Workshop243Quiz1.What four new HTML5 features help with form usability?2.What are the new date and time input types?3.Name some of the styles that are difficult to change in WebKit browsers onthe <input type=search>field.4.What is the <output>element used for?5.What attributes c...

  • Page 265

    ptg999This page intentionally left blank actionURI(http://www.freepdf-books.com /):www.freepdf-books.com http://freepdf-books.com

  • Page 266

    ptg999The New Contenteditable Attribute245 10,HOUR 10,14 10,Editing Content and 10,User 10,Interaction with HTML5What You’ll Learn in This Hour:. How to edit content online with contenteditable. How to make a rich text editor with execCommand. How to check spelling in forms. How to use new f...

  • Page 267

    ptg999▼246HOUR 14: Editing Content and User Interaction with HTML5attribute really isn’t new. It’s been supported in every major desktop browser, includ-ing Chrome, Firefox 3, Internet Explorer 5.5, Opera 9, and Safari 3, for a long time.To use this attribute, simply add it to an element yo...

  • Page 268

    ptg999The execCommandMethod247By theWay3.Add some buttons for your editor:<input type=button id=bold value=B><input type=button id=italic value=i><input type=button id=underline value=U><input type=button id=createlink value=a>4.Add jQuery to your document:<script src=...

  • Page 269

    ptg999248HOUR 14: Editing Content and User Interaction with HTML5TABLE 14.1Commands Supported by execCommandCommandValueDescriptionbackcolorColor valueChanges the document backgroundcolor. In IE this changes the textbackground color.boldToggles bold on and off.createlinkURLCreates an <a href=...

  • Page 270

    ptg999The execCommandMethod249TABLE 14.1Commands Supported by execCommandCommandValueDescriptionjustifyleftSets text alignment to left withtext-align: left;.justifyrightSets text alignment to right withtext-align: right;.outdentRemoves indents created by theindent command. This commandremoves any...

  • Page 271

    ptg999▼250HOUR 14: Editing Content and User Interaction with HTML5Browsers Interpret the Editor DifferentlyThe browsers that support the contenteditableattribute and the execCommandfunction do so in slightly different ways. For example, Internet Explorer applies allthe fields to selected text. ...

  • Page 272

    ptg999Adding Spellcheck to Web Pages251Of course, this to-do list isn’t very useful, because as soon as you leave thepage, it disappears. Therefore, add a jQuery script to save it to local storage(also covered in Hour 21), and restore it when the page reloads.3.Add jQuery to the head of your do...

  • Page 273

    ptg999252HOUR 14: Editing Content and User Interaction with HTML5The challenge with the spellcheckattribute is browser support. Internet Explorer,Safari, iOS, and Android don’t support the spellcheckattribute. However, except forIE, they all offer alternatives that are built into the browser. C...

  • Page 274

    ptg999Additional UI Components of HTML5253 10,Additional UI Components 10,of HTML5Several aspects of user interaction are carried forward from HTML 4 to HTML5, butthe one thing that makes HTML5 unique is that now these features can be applied toany element.These UI features include:. Activation ...

  • Page 275

    ptg999254HOUR 14: Editing Content and User Interaction with HTML5. onemptied—The videoor audioelement returns to the uninitialized state.. onended—The end of the videoor audioelement is reached.. onerror—The element failed to load properly.. oninvalid—The element, usually a form field, di...

  • Page 276

    ptg999Browser Support of UI and Editing Features255. onvolumechange—The DOM attribute volumeor the DOM attribute mutedhas changed on the videoor audioelement.. onwaiting—Playback of the videoor audioelement has stopped becausethe next frame is not yet available.The most useful change is the a...

  • Page 277

    ptg999256HOUR 14: Editing Content and User Interaction with HTML5However, editing content in a mobile application is impossible. Thecontenteditableattribute is not supported in any mobile browser at this time.Instead, you need to use a <textarea>element and provide a plain HTML (not richtex...

  • Page 278

    ptg999Summary257WatchOut!Be Careful with “False”All of these attributes (contenteditable, spellcheck, and hidden) are booleanattributes. As such, they imply the values true and false—true when the attributeis present and false when it is not. But many web browsers treat the presence ofthe a...

  • Page 279

    ptg999258HOUR 14: Editing Content and User Interaction with HTML5You also learned about the new UI attribute hidden, which can be placed on any ele-ment to hide it from view. 10,Q&AQ.If contenteditablehas been around so long, why have I only just nowheard of it?A.This attribute was created by...

  • Page 280

    ptg999Workshop259Quiz1.What browsers support contenteditable?2.What elements can use the contenteditableattribute?3.What attribute do you need to create a rich text editor in your browser?4.There is a “gotcha” in detecting for contenteditable—what is it?Exercises1.Build a to-do list that in...

  • Page 281

    ptg999This page intentionally left blank actionURI(http://www.freepdf-books.com /):www.freepdf-books.com http://freepdf-books.com

  • Page 282

    ptg999Using Microformats261 10,HOUR 10,15 10,Microformats and MicrodataWhat You’ll Learn in This Hour:. How to mark up HTML semantically with more than just HTML elements. Why semantic markup is important. The differences between RDFa, microdata, and microformats. How to choose between microf...

  • Page 283

    ptg999262HOUR 15: Microformats and MicrodataSome things you can mark up with microformats include:. Events using hCalendar—With hCalendaryou can indicate the start dateand time, end date and time, and location of an event.. Contact information using hCard—The hCardmicroformat lets you addvcar...

  • Page 284

    ptg999Using Microformats263<h1>Jennifer Kyrnin&#8217;s review:</h1>...</article></article>When you read the review, you know which parts are the book title, author, and rat-ing, but a computer would have no idea. There would be no reasonable way to getthis review infor...

  • Page 285

    ptg999264HOUR 15: Microformats and MicrodataFor example, on Goodreads you can find 150 reviews of the book Dopplegangster. Youcan find 18 reviews on Amazon.com and 40 reviews in Google books, with averageratings of 3.59, 4.33, and 3.5 (approximately), respectively.If all these reviews were marked...

  • Page 286

    ptg999Using Microformats265. hReview—For writing reviews of products, businesses, events, and so on. rel-nofollow—To tell search engines not to afford additional weight tothe link. XHTML Friends Network (XFN)—Represents human relationships insidelinkshCardand hCalendarare both widely suppor...

  • Page 287

    ptg999266HOUR 15: Microformats and MicrodataSet the Phone Number Type CorrectlyWhen you define the type of your phone number, you need to use one of the typeslisted in the hCardinstructions: home, work, pref, fax, cell, voice, video, pager,car, msg, modem, bbs, isdn, or pcs. These types are not c...

  • Page 288

    ptg999Using Microdata2676.Define the email address with an emailclass:<a href=”mailto:jennifer@example.com”➥class=”email”>jennifer@example.com</a>7.Add elements to the address so that you can add hCardclasses:<h4>Address:</h4><p class=”adr”><span cla...

  • Page 289

    ptg999▼268HOUR 15: Microformats and Microdata<p>Review Date:<time datetime=”2010-12-15” itemprop=”dtreviewed” pubdate>December 15,2010</time></span><article itemprop=”description”><h3><span itemprop=”reviewer vcard fn” id=”reviewer”>...

  • Page 290

    ptg999Using RDFa2693.Set the itemtypeto hCard:<address itemscope itemtype=”http://microformats.org/profile/hcard”class=”vcard”>4.Remove the class from the container element, because it is defined by theitemtype:<address itemscope itemtype=”http://microformats.org/profile/hcard...

  • Page 291

    ptg999270HOUR 15: Microformats and Microdata. rev—A reverse relationship with another resource. hrefor resource—The URL of the resource. property—A characteristic of the element’s contentTo mark up an address in RDFa, you need to use the VCARD-RDF specification. Youalso need to add the na...

  • Page 292

    ptg999Mobile and Microformats271By theWayRDFa is based on RDF and can be complicated to learn. However, many tools areavailable for adding RDF and RDFa to your documents. RDFa works best withXHTML, rather than the less strict HTML and is very popular in academia.Microdata is the newest tool. It i...

  • Page 293

    ptg999272HOUR 15: Microformats and MicrodataThe phone would simply know that that data (with the microformat codes) was acoordinate to map.Two Less Formalized MicroformatsMobile devices are also starting to regularly use two other microformats: nanofor-mats and picoformats. These are microformats...

  • Page 294

    ptg999Q&A273Deciding between using microformats, microdata, and RDFa might be tricky, but itboils down to this:. Microformats are the easiest to use.. RDFa has a lot of support.. Microdata is a W3C standard.The smallest microformats—nanoformats and picoformats—let you mark up textwith ver...

  • Page 295

    ptg999274HOUR 15: Microformats and MicrodataQ.Microdata and microformats seem complicated—how can I make sure I’veadded them correctly?A.You can use validators to check your microformats and microdata. The W3Chas an RDF validator actionURI(www.w3.org/RDF/Validator/):(www.w3.org/RDF/Validator/...

  • Page 296

    ptg999Implementing Drag and Drop275 10,HOUR 10,16 10,Working 10, with 10, HTML5 10, Drag- 10,and-Drop FunctionalityWhat You’ll Learn in This Hour:. Why drag and drop is important for web applications. How to use drag and drop in most modern browsers. How to use the new events and attributes f...

  • Page 297

    ptg999276HOUR 16: Working with HTML5 Drag-and-Drop FunctionalityWatchOut!location. On Android devices, the drag and drop occurs when the user taps andholds an object and then slides to a new location and lets go.The two ways to implement drag and drop are generally referred to as “old school”...

  • Page 298

    ptg999Drag-and-Drop Events277. dragend—Kicks off when the drag stops. drop—Kicks off when the element is droppedThe challenge is that browsers handle these events differently. You can see an exam-ple of this in how the browsers handle displaying the drag operation. Figure 16.1shows you the sa...

  • Page 299

    ptg999278HOUR 16: Working with HTML5 Drag-and-Drop Functionality$(‘.dragableObject’).bind(‘dragstart’, function(ev) {var dt = ev.originalEvent.dataTransfer;dt.setData(“Text”, “Dropped in zone!”);return true;}).bind(‘dragend’, function(ev) {return false;});Use the Drag Event Sp...

  • Page 300

    ptg999Drag-and-Drop Attributes279. dataTransfer.setDragImage(element, x, y)—Uses the specified imageelement instead of the browser default and places it at x, ycoordinates off-set from the cursor.. dataTransfer.addElement(element)—Adds the specified image elementto the list of elements used t...

  • Page 301

    ptg999280HOUR 16: Working with HTML5 Drag-and-Drop FunctionalityFirefox needs the draggableattribute on any element other that an <img>or<a>. Otherwise, it treats the drag as a selection. Internet Explorer doesn’t needeither attribute. Safari will drag a draggableelement, and will d...

  • Page 302

    ptg999Building a Drag-and-Drop Interface2813.Define a drop zone.4.Set events on the drop zone.5.Pass information between the object and the drop zone.6.Define the effects for the drag-and-drop operation.The following sections discuss these steps in detail.Defining a Draggable ObjectTo define a dr...

  • Page 303

    ptg999282HOUR 16: Working with HTML5 Drag-and-Drop FunctionalityDefining a Drop ZoneThe drop zone is where the dragged item should be dropped. Define the drop zonewith the dropzoneattribute:<div id=”dropZone” dropzone=”copy”><p>Drop Items Here</div>Use CSS to Highlight D...

  • Page 304

    ptg999Building a Drag-and-Drop Interface283WatchOut!function drop(target, e) {var id = e.dataTransfer.getData(‘Text’);target.appendChild(document.getElementById(id));e.preventDefault();}Preventing the default action with the e.preventDefault();line is especiallyimportant in Firefox. If you le...

  • Page 305

    ptg999▼284HOUR 16: Working with HTML5 Drag-and-Drop FunctionalityIn the code above, the dataTransfer.effectAllowedis copy, while thedataTransfer.dropEffectis move. Because these aren’t both copyor both move,the drag-and-drop function won’t work.Most of the time you can leave the effects alo...

  • Page 306

    ptg999Building a Drag-and-Drop Interface285</div></div></body></html>3.Add the drop, dragenter, and dragoverevents to the drop zones:<div id=”place1” ondrop=”drop(this, event);”ondragenter=”return false;” ondragover=”return false;”></div><div...

  • Page 307

    ptg999286HOUR 16: Working with HTML5 Drag-and-Drop Functionality8.Loop through the images, and display them on the page:for (i=0; i<12; i++) {$(‘#pieces’).append(“<img ➥src=\”/examples/images/puzzle/”+images[i]+”\”➥id=\”piece”+i+”\” draggable=true ondragstart=\”d...

  • Page 308

    ptg999Using Drag and Drop on iOS287border: solid black 0.3em;width: 60em;height: 80em;}#puzzle-frame > div {width: 20em;height: 20em;float: left;}#pieces {width: 20em;float: left;margin-right: 0.5em;}You can see this puzzle in action at actionURI(www.html5in24hours.com/examples/drag-and-drop-p...

  • Page 309

    ptg999288HOUR 16: Working with HTML5 Drag-and-Drop FunctionalityYou can set several options to the draggable item:. revert—This is a boolean option that, if set to true, will return the drag-gable element to its starting location unless it is successfully dragged to avalid drop zone. You can al...

  • Page 310

    ptg999▼Using Drag and Drop on iOS289Try It YourselfBuilding a Drag-and-Drop Page for an iPhone or iPadIncluding drag and drop on iOS devices is important for many web applications,and this Try It Yourself shows you how to do it, even without HTML5.1.Download the GotProject webkit drag-and-drop ...

  • Page 311

    ptg999290HOUR 16: Working with HTML5 Drag-and-Drop Functionality9.Close your HTML.</body></html>You can see an example of this drag-and-drop operation at actionURI(www.html5in24hours.com/examples/drag-and-drop-examples-ios.html):www.actionURI(www.html5in24hours.com/examples/drag-and-d...

  • Page 312

    ptg999Workshop291 11,WorkshopThe workshop contains quiz questions to help you process what you’ve learned inthis chapter. Try to answer all the questions before you read the answers. SeeAppendix A, “Answers to Quizzes,” for answers.Quiz1.What are the two best elements to make draggable and ...

  • Page 313

    ptg999This page intentionally left blank actionURI(http://www.freepdf-books.com /):www.freepdf-books.com http://freepdf-books.com

  • Page 314

    ptg999How Links Have Changed in HTML5293 11,HOUR 11,17 11,HTML5 LinksWhat You’ll Learn in This Hour:. How to make changes to hyperlinks using the <a>and <area>elements. How to link elements on your pages. How to add empty links. New relationships with new link typesLinks are found...

  • Page 315

    ptg999294HOUR 17: HTML5 Links. All three linking elements have a bunch of new relationships that you canapply using the relattribute.Hyperlinks and External ResourcesLinks in an HTML document represent a connection between two documents—thecurrent document and the one referenced in the link. Th...

  • Page 316

    ptg999How Links Have Changed in HTML5295WatchOut!You would then link to that location with a link with a hash tag:<a href=”#block”>Linking Block-level Elements</a>But modern web browsers recognize the idattribute as a unique identifier, and soyou can point to them directly without...

  • Page 317

    ptg999296HOUR 17: HTML5 LinksDid youKnow?entire paragraph or headline and surrounding text, you needed to add the link mul-tiple times.For example, to link a headline, image, and block of text to the same place in HTML4 you had to write:<h3><a href=”garden.html”>Come See our New G...

  • Page 318

    ptg999How Links Have Changed in HTML5297WatchOut!placeholders for links that don’t have pages to point to yet, such as in a designmockup.Link Pseudo-Classes Don’t Always Work on Placeholder LinksThe :linkand :visitedpseudo-classes won’t work when you’re styling place-holder links. This ma...

  • Page 319

    ptg999298HOUR 17: HTML5 LinksFIGURE 17.1A list with onehidden link inChrome.The hiddenand contextmenuattributes add some additional features that are espe-cially useful for links.You can use the hiddenattribute to hide links inside pages where they are not rele-vant. This can be useful when maint...

  • Page 320

    ptg999Link Types and Relationships299 11,Link Types and RelationshipsHTML5 links involve more than just hyperlinks. Although the <link>element hasn’tchanged a lot directly, one aspect of these links has changed a fair amount: linkrelationships.You define link relationships (on both hyperl...

  • Page 321

    ptg999300HOUR 17: HTML5 LinksTABLE 17.1Link Types and Their Effect on Link ElementsLink TypeEffect on...<a> and <area><link>alternateHyperlinkHyperlinkauthorHyperlinkHyperlinkbookmarkHyperlinkNot allowedexternalHyperlinkNot allowedhelpHyperlinkHyperlinkiconNot allowedExternal re...

  • Page 322

    ptg999Using the New Link Types301Did youKnow?users and search engines information about the site structure. For example, you linkto the Spanish version of a page by writing:<a href=”http://es.html5in24hours.com/” rel=”alternate” hreflang=”es”>Google Also Supports the canonical T...

  • Page 323

    ptg999302HOUR 17: HTML5 LinksMost browsers don’t do anything special for these link types. However, identifyingexternal links for your customers can be useful. You can also use this attribute toopen external links in a new window with a script. In jQuery, just append the tar-get=_blank attribut...

  • Page 324

    ptg999Using the New Link Types303The Nofollow and Noreferrer TypesThe nofollowtype tells search engine robots not to follow the link, or if they do fol-low it, not to pass along any page rank. However, just because you’ve put thisattribute on a link doesn’t mean that that page won’t be foun...

  • Page 325

    ptg999304HOUR 17: HTML5 LinksYou can add multiple types to one link by separating them with a space in the relattribute, for example:<a href=”http://spam.com” rel=”nofollow noreferrer”>The Pingback TypeThe pingbacktype provides a link to the pingback server for the page. Pingbackser...

  • Page 326

    ptg999Using the New Link Types305The Sidebar Link TypeThe sidebarlink type is currently only supported by Firefox and Opera. When aFirefox user clicks a link with the rel=sidebarattribute, it opens in a sidebar win-dow in the browser. Figure 17.2 shows a Firefox page with a sidebar open.Browsers ...

  • Page 327

    ptg999306HOUR 17: HTML5 Links 11,SummaryHTML5 made some changes to the <a>element that make it easier to use and thatmakes it conform to how browsers are already displaying. In this hour you learnedthat you can now link block-level elements and create placeholder links with empty<a>el...

  • Page 328

    ptg999Workshop307Using these relationships if they are appropriate is perfectly acceptable, but astrict validator might mark your document invalid.Q.You mentioned that the nameattribute is obsolete, but what does that mean?A.In HTML5, an obsolete feature is one that can be used but that will trig...

  • Page 329

    ptg999308HOUR 17: HTML5 LinksExercises1.Build a page for a specific media type, such as a tablet or smart phone,then create a link to that page using the mediaattribute and mediaqueries, like you learned in Hour 4, “Detecting Mobile Devices and HTML5Support.”2.Build an author page for all the...

  • Page 330

    ptg999Creating Web Applications309 11,HOUR 11,18 11,Web 11, Application 11, APIs 11, and 11,DatasetsWhat You’ll Learn in This Hour:. What a web application and an API are. How web applications are changing the web. The APIs that make up HTML5 web applications. How to access custom data in web...

  • Page 331

    ptg999310HOUR 18: Web Application APIs and DatasetsWeb Application APIsAn API, or application programming interface, is a list of instructions for how towrite different programs. Web application APIs are the JavaScript methods and func-tions that support a given API.Modern web applications use th...

  • Page 332

    ptg999Creating Web Applications311. ondblclick. ondrag. ondragend. ondragenter. ondragleave. ondragover. ondragstart. ondrop. ondurationchange. onemptied. onended. onformchange. onforminput. oninput. oninvalid. onkeydown. onkeypress. onkeyup. onloadeddata. onloadedmetadata. onloadstart. onmousedo...

  • Page 333

    ptg999312HOUR 18: Web Application APIs and DatasetsFollowing are event handlers that can be placed on Window objects such as <body>and <frameset>:. onafterprint. onbeforeprint. onbeforeunload. onblur. onerror. onfocus. onhashchange. onload. onmessage. onoffline. ononline. onpagehide. ...

  • Page 334

    ptg999Creating Web Applications313There is also an error event: onerror, as well as an event when the form submissiondoes not meet validity constraints: oninvalid.Click Events on iOS Work DifferentlyIf you’re creating an application that uses the scripting API onclickevents to trig-ger actions ...

  • Page 335

    ptg999▼314HOUR 18: Web Application APIs and DatasetsTry It YourselfBuilding a Script that Rotates the Background ColorThis script will use both the onclickevent handler that you are probably alreadyfamiliar with and the setInterval()method to change the background color ofa div.1.Open an HTML d...

  • Page 336

    ptg999Creating Web Applications3158.Write the bgColorChange()function:function bgColorChange() {var box = document.getElementById(“changeColorBox”);if (box.style.backgroundColor == ‘red’) {box.style.backgroundColor = ‘orange’;box.style.color = ‘black’;} else {box.style.backgroundC...

  • Page 337

    ptg999▼316HOUR 18: Web Application APIs and DatasetsWatchOut!FIGURE 18.1Three simpleprompts on aniPad.The most interesting type of user prompt is the modal dialog. This box opens a sep-arate page in a new window. This makes web applications act even more like desk-top applications.Modal Dialogs...

  • Page 338

    ptg999Creating Web Applications3173.Build a second page for your modal dialog:<!DOCTYPE HTML><html><head><meta charset=”UTF-8”><title>Modal</title><script>function hours() {var text = document.getElementById(“text”);window.returnValue=text.value;w...

  • Page 339

    ptg999318HOUR 18: Web Application APIs and DatasetsBy theWayBy theWay<p id=”uaHandler”><strong>Full User Agent Handler:</strong><br/></p><script>$(document).ready(function(){var browser = window.navigator.appName;var version = window.navigator.appVersion;va...

  • Page 340

    ptg999Datasets and data-*Attributes319Did youKnow?from difficult to just crazy. Some developers use HTML with a custom DTD tocover the extra data fields. Others use the classattribute to hold data as well asstyle information. Still others use XHTML with namespaces to define the extrafields. Datas...

  • Page 341

    ptg999320HOUR 18: Web Application APIs and DatasetsTABLE 18.1JavaScript and DatasetsJavaScript MethodsDataset MethodsgetAttribute(“data-dataName”)dataset.dataNamesetAttribute(“data-dataName”, “new value”)dataset.dataName = “new value”removeAttribute(“data-dataName”)dataset.dat...

  • Page 342

    ptg999Workshop321Applications.” The onstorageevent handler refers to using web storage tostore data, which is covered in Hour 21, “Web Storage in HTML5.”Q.I read that I can add things such as date stamps or other information toprinted pages using an event handler. How does that work?A.HTML5...

  • Page 343

    ptg999322HOUR 18: Web Application APIs and DatasetsQuiz1.What are two things that differentiate a web application from a web page?2.Name the four ways a script can be fired in a web application.3.Which is better to use to get data from a dataset—the JavaScript getAttributemethod or the datasetm...

  • Page 344

    ptg999Two-Way Communication with WebSockets323 11,HOUR 11,19 11,WebSockets, 11,Web 11, Workers, 11,and FilesWhat You’ll Learn in This Hour:. How to use WebSockets to speed up web communication. Why WebSockets aren’t fully supported. How to thread JavaScript with Web Workers. How to use the...

  • Page 345

    ptg999324HOUR 19: WebSockets, Web Workers, and FilesBy theWayWebSocket Security ConcernsThe problem that Firefox and Opera browser manufacturers have with WebSocketsis a security concern that is not browser specific. The problem is that the handshakethat sets up WebSockets connections can be expl...

  • Page 346

    ptg999Two-Way Communication with WebSockets325server at regular intervals, and the server responds. Long-polling is where the browsersends a request to the server and the server keeps the request open for a set period oftime. If a response comes in during that time, the server sends it immediatel...

  • Page 347

    ptg999326HOUR 19: WebSockets, Web Workers, and FilesPay Attention to Protocol VersionsOne of the challenges to implementing WebSockets right now is that your socketsserver must be constantly updated. Chrome 6.4 stopped supporting version 75 ofthe protocol (and lower) and Google continues to make ...

  • Page 348

    ptg999▼Running Scripts in the Background with Web Workers327To add a new Worker to your script, you write:worker = Worker(“worker.js”);You can then communicate with your Worker by watching for a message from it:worker.onmessage = function(e){e.data};and sending messages to it:worker.postmes...

  • Page 349

    ptg999328HOUR 19: WebSockets, Web Workers, and Files2.Add a listener to the file to listen for events calling the Worker:// event listenerthis.onmessage = function (event) {var data = event.data;switch(data.func) {case ‘add’:postMessage(addNumbers(data.one, data.two));break;case ‘subtract...

  • Page 350

    ptg999Running Scripts in the Background with Web Workers329<title>Web Workers Example</title><script src=”jquery.min.js”></script></head><body>5.Build your calculator:<h1>A Calculator</h1><p><button id=one class=number>1</button&g...

  • Page 351

    ptg999330HOUR 19: WebSockets, Web Workers, and Files7.Initialize your Web Worker inside a script that checks whether the browser sup-ports Workers:<script>if (supportsWorkers() ) {worker = new Worker(“worker.js”);// Watch for messages from the workerworker.onmessage = function(e){$(“#...

  • Page 352

    ptg999Handling Client-Side Files with the File API331By theWaynext = 0;});This resets the nextvariable and empties the three fields.11.Write the function for when the equal sign is clicked:$(“#submit”).click(function() {two = parseFloat($(“#second”).val());message = {‘func’ : func,‘...

  • Page 353

    ptg999332HOUR 19: WebSockets, Web Workers, and FilesFIGURE 19.1A calculatorapplication inFirefox.By theWayThe File API includes several interfaces, including:. FileList—An array of individual files selected from the underlying file system. File—Read-only information about the file, including ...

  • Page 354

    ptg999Handling Client-Side Files with the File API333WatchOut!The File API is supported in Android 3.0, Chrome 6, Firefox 3.6, Opera 11.1, andSafari 5.1. So for IE and iOS, you need to detect it and use standard file uploading forthose browsers. Here is a simple detection script:if (!fileAPI()) {...

  • Page 355

    ptg999334HOUR 19: WebSockets, Web Workers, and FilesGetting the File InformationThe files are sent to the application as an array of files in the FileList. You canthen iterate across this array to get the name, size, and MIME type of each file.In this example, the getImages()function reads the fi...

  • Page 356

    ptg999▼Handling Client-Side Files with the File API335if (!file.type.match(‘image.*’)) {continue;}var reader = new FileReader();reader.onload = (function(theFile) {return function(e) {var span = document.createElement(‘span’);$(‘<span/>’).addClass(“preview”).html(“<im...

  • Page 357

    ptg999336HOUR 19: WebSockets, Web Workers, and Files3.Add a progress bar box:<div id=”progress”></div>4.Style these boxes how you like.5.Put your <script>element at the bottom of the document, just above the</body>:<script></script>6.In the jQuery document ...

  • Page 358

    ptg999Summary3379.Run the uploadFilesfunction. Be sure to check that the files are types andsizes you want:function uploadFiles(files) {var i, file;for (i=0; i<files.length; i++) {file = files[i];// make sure they are only image typesif (!file.type.match(‘image.*’)) {continue;}// make sure...

  • Page 359

    ptg999338HOUR 19: WebSockets, Web Workers, and FilesYou learned about creating bidirectional connections to web applications with theWebSockets API. This API allows you to connect with WebSockets servers and provideclose to real-time data to your customers.This hour also covered Web Workers. Web ...

  • Page 360

    ptg999Workshop339function FileUpload(files) {for (var i=0; i<files.length; i++) {var file = files[i];// make sure they are only image typesif (!file.type.match(‘image.*’)) {continue;}// build file listvar reader = new FileReader();var xhr = new XMLHttpRequest();this.xhr = xhr;xhr.upload.ad...

  • Page 361

    ptg999340HOUR 19: WebSockets, Web Workers, and FilesExercises1.Rewrite the calculator application so that it calculates the numbers in onetext field, as in a standard calculator. Make the operators do calculationsimmediately, so that you can add (subtract, and so on) more than just twonumbers. Yo...

  • Page 362

    ptg999Building Offline App and Converting Apps to Work Offline341 11,HOUR 11,20 11,Offline Web ApplicationsWhat You’ll Learn in This Hour:. Why you would build offline applications. How to use the cache manifest. How to debug and solve problems with your cached applications. How to detect the...

  • Page 363

    ptg999342HOUR 20: Offline Web ApplicationsAn offline web application takes a list of files for your web application and down-loads them to an offline cache in the browser. Then when the web browser is offlineit uses the cached copies of those files to build your application.You Must Store User Da...

  • Page 364

    ptg999The Cache Manifest343By theWayYou need to do just a couple of things to convert your application into an offlineapplication:1.Create a cache manifest that includes every file (including images, CSS, andJavaScript) that your application uses.2.Add the cache manifest to every HTML file with &...

  • Page 365

    ptg999344HOUR 20: Offline Web ApplicationsSome user agents do this automatically, and others ask the users whether they wantto cache the application, as shown in Figure 20.1.Writing a Cache ManifestThe simplest cache manifest has just the explicit section that details the files thatshould be cach...

  • Page 366

    ptg999The Cache Manifest345WatchOut!By theWayThe files are listed relative to the location of the cache manifest file. Because there isno directory information, you know that these files are in the same directory as thecache manifest. But you can also use full URLs, like this:actionURI(http://www...

  • Page 367

    ptg999▼346HOUR 20: Offline Web ApplicationsThe fallback section gives you a way to specify what the user agent should do if apage is not available offline. The fallback section looks like this:FALLBACK:/ /offline.htmlThe first part of that line is a pattern that describes what files should have...

  • Page 368

    ptg999Using DOM Events and Properties for Offline Apps347By theWay4.Set the online whitelist wildcard flag in the cache manifest:NETWORK:*5.On every page that you want to be available offline, add the cache manifest tothe <html>element:<html manifest=”/cache.manifest”>Then, whenev...

  • Page 369

    ptg999▼348HOUR 20: Offline Web ApplicationsAnother useful tool is the navigator.onLineproperty. This property reports backthe current online or offline state of the user. This is important to know so that youdon’t attempt to access online resources when a browser is offline. For example,when ...

  • Page 370

    ptg999Using DOM Events and Properties for Offline Apps3493.Add the HTML elements including a button to recheck the cache and an area todisplay the events:<h1>Offline Web Apps&#8212;Listening for Cache Events</h1><h2><span id=”status”>Online</span> &#8211;...

  • Page 371

    ptg999350HOUR 20: Offline Web Applications}).bind(“obsolete”, function(e) {writeEvent(“Manifest not found”);}).bind(“error”, function(e) {writeEvent(“An error occurred”);});7.The last thing that you should do is bind the click action when the check cachebutton is clicked. Add this...

  • Page 372

    ptg999Debugging the Application Cache351WatchOut! 11,Debugging the Application 11,CacheThe challenge of using the application cache is that most errors will cause thecaching to completely fail, with no indication of what the problem was. The errorevent will fire and the caching will stop.Your We...

  • Page 373

    ptg999352HOUR 20: Offline Web ApplicationsTo swap in the new cache with jQuery, write:var appCache = window.applicationCache;$(appCache).bind(“updateready”, function(e){appCache.swapCache();}); 12,SummaryThis hour you learned how to convert an online application to an offline one. Youlearned ...

  • Page 374

    ptg999Workshop353Q.Is there a way to use wildcards to create my explicit section in the cachemanifest?A.Although the possibility exists that some browsers support wildcards to definethe cached files, the fact is that this isn’t part of the specification, and mostbrowsers don’t support them. I...

  • Page 375

    ptg999354HOUR 20: Offline Web Applications3.What is the first line of the cache manifest and what MIME type must it beserved as?4.What are the fallback and whitelist sections used for?Exercises1.Build a cache manifest for a site that has a lot of pages. The pages shouldall be added to the cache w...

  • Page 376

    ptg999355 12,HOUR 12,21 12,Web 12, Storage 12, in 12, HTML5What You’ll Learn in This Hour:. How to use local storage. How to detect local storage support. When to use local storage versus cookies. How to add local databases using Web SQL and Indexed DB. How to build an application that uses l...

  • Page 377

    ptg999356HOUR 21: Web Storage in HTML5By theWay 12,What 12,Is Web Storage?Web storage is a separate API that was originally part of the HTML5 specification,but now is a separate document within the aegis of HTML5. It is sometimes calledLocal Storage or DOM Storage depending upon the browser manu...

  • Page 378

    ptg999What Is Web Storage?357Did youKnow?Remember that web storage is not just a better cookie. Cookies serve a purpose andyou should continue to use them. For example, cookies have two flags, HttpOnlyand secure, that help make cookies safer. The HttpOnlyflag tells the browser thatthis cookie sho...

  • Page 379

    ptg999358HOUR 21: Web Storage in HTML5Local storage is best for storing non-sensitive data that takes up a lot of space. It isfor data that needs to be saved across sessions so that users have access to it whenthey return to the site.Session storage is name/value pairs that are stored on the loca...

  • Page 380

    ptg999▼What Is Web Storage?359. window.localStorage. window.sessionStorageAs with other objects, the windowportion is assumed.Try It YourselfSaving Gift Status in an E-commerce StoreIn online stores, a user can easily accidentally click away or close the browser win-dow and lose his or her choi...

  • Page 381

    ptg999360HOUR 21: Web Storage in HTML54.In the web storage functions area, add the sessionStorageobject for when theuser clicks the checkbox:$(“#gift”).click(function() {if ($(this).attr(‘checked’)) {sessionStorage.setItem(“gift”, “yes”);} else {sessionStorage.setItem(“gift”, ...

  • Page 382

    ptg999Web SQL and Indexed DB361WatchOut!Web Storage Can Be HackedAs with cookies, web storage can be hacked if your site is not secured againstcross site scripting (XSS). The name of any items you store in local storage iswritten in clear text inside your JavaScript, so a hacker can easily use XS...

  • Page 383

    ptg999362HOUR 21: Web Storage in HTML5Web SQL Has Been DiscontinuedOn November 18, 2010, the W3C decided to discontinue development of the WebSQL specification. It is still supported by some browsers, and it could be revisitedin the future, but right now it is not being worked on and there are no...

  • Page 384

    ptg999Web SQL and Indexed DB363WatchOut!tx.executeSql(‘INSERT INTO names (id, text) VALUES (2, “Sarah”)’);});SQLite Ignores Data TypesWhen you are inserting data into a database with Web SQL, you are inserting itinto an SQLite database, and SQLite ignores data types. It just uses simplest...

  • Page 385

    ptg999364HOUR 21: Web Storage in HTML5You have to set up the database for a first-time user:req.onsuccess = function(e) {var db = e.result;if (db.version != “1”) {//first visit, initialize databasevar createdObjectStoreCount = 0;var objectStores = [{ name: “fnames”, keypath: “id”, aut...

  • Page 386

    ptg999▼Web SQL and Indexed DB365alert(“‘Jennifer’ added to database with id “ + e.result);};};To list all the items in a table you would use the openCursor()method, and enu-merate through it until it returned null:req.onsuccess = function(e) {req = e.result.objectStore(“fnames”).ope...

  • Page 387

    ptg999366HOUR 21: Web Storage in HTML5<p>Birthday:<select id=”birthdayMonth” required><option value=”0”>January<option value=”1”>February<option value=”2”>March<option value=”3”>April<option value=”4”>May<option value=”5”>...

  • Page 388

    ptg999Web SQL and Indexed DB367function initWebSqlDb(db) {db.transaction(function(tx) {tx.executeSql(‘CREATE TABLE IF NOT EXISTS birthdays(➥id integer primary key autoincrement, fullname, birthdayMonth,➥birthdayDay)’);});// load current month’s birthdaysvar thisMonth = new Date().getMon...

  • Page 389

    ptg999368HOUR 21: Web Storage in HTML5function getMonthName(month) {month = parseInt(month);switch(month) {case 0:month = “January”;break;case 1:month = “February”;break;case 2:month = “March”;break;case 3:month = “April”;break;case 4:month = “May”;break;case 5:month = “June...

  • Page 390

    ptg999Web SQL and Indexed DB369$(“#next”).attr(“class”, monthNum);$(“#thisMonth”).html(thisMonthIs);});8.Add the “next” and “previous” button support into the document ready function:$(“#prev”).click( function(e) {var curMonth = $(this).attr(“class”);var newMonth = par...

  • Page 391

    ptg999370HOUR 21: Web Storage in HTML5createTableRow(results.insertId,inputFullName,➥prettyMonth,inputBirthdayDay,”birthdays”);}});});}function removeBirthdayWebS(id) {db.transaction(function(tx) {tx.executeSql(‘DELETE FROM birthdays WHERE id=?’, [id],➥function() {//Dynamically remove...

  • Page 392

    ptg999Q&A371 12,Q&AQ.If web storage is supported by all major browsers, shouldn’t I just use itinstead of cookies?A.As mentioned in this hour, cookies still have a valid purpose. They can bemore secure, and so using them for session IDs is important. Plus, cookies aremore familiar to mo...

  • Page 393

    ptg999372HOUR 21: Web Storage in HTML5 12,WorkshopThe workshop contains quiz questions to help you process what you’ve learned inthis chapter. Try to answer all the questions before you read the answers. SeeAppendix A, “Answers to Quizzes,” for answers.Quiz1.What are three differences betwe...

  • Page 394

    ptg999Why Control the Browser History?373 12,HOUR 12,22 12,Controlling the Browser 12,History with the History 12,APIWhat You’ll Learn in This Hour:. How to control the browser history. How to add pages to the history to add forward and back navigation indynamic sites. Methods to navigate th...

  • Page 395

    ptg999374HOUR 22: Controlling the Browser History with the History APIWatchOut!While you can change the history to play games or mess around with the browsers,the most important reason for manipulating the browser history is to give yourreaders a way to navigate through your applications. Before ...

  • Page 396

    ptg999Using the History API375 12,History API MethodsThe three history methods you should already be familiar with are. history.back()—This takes the user back one step in the history.. history.forward()—This takes the user forward one step in the history.. history.go()—This allows the user...

  • Page 397

    ptg999376HOUR 22: Controlling the Browser History with the History APIwhen you use the History API, you need to have fallback options for InternetExplorer and older browsers.To check for support of the History API:if (hasHistoryApi()) {// write your scripts here} else {// fallback options}functio...

  • Page 398

    ptg999Using the History API377margin: 0 0 0 -2em;padding: 0.5em;}li:nth-child(even) { background-color:#dfdfdf; }#prev {background: url(images/arrow_left.png) no-repeat;padding-left: 1.8em;}#next {background: url(images/arrow_right.png) no-repeat 3em;padding-right: 1.8em;}</style></head&...

  • Page 399

    ptg999378HOUR 22: Controlling the Browser History with the History APIfunction getArticleList(page) {var length = articles.length;var counter = (parseInt(page)-1)*10 +10;var index = (parseInt(page) -1) * 10;var lastItem = index+10 > length ? length : index+10;// set page number$(“#pageNum”...

  • Page 400

    ptg999Using the History API379You can see this page online at actionURI(www.html5in24hours.com/examples/history-api-example-no-history.html):www.html5in24hours.com/examples/actionURI(www.html5in24hours.com/examples/history-api-example-no-history.html):history-api-example-no-history.html.When you ...

  • Page 401

    ptg999▼380HOUR 22: Controlling the Browser History with the History APIvar stateObject = {title: ‘History API Examples - Page ‘+page,createdOn: date,author: ‘Jennifer Kyrnin’};You then include that variable in your pushStatecall:history.pushState(stateObject, null, newUrl);The Title Is ...

  • Page 402

    ptg999Using the History API381<article id=”photogallery”><h1>Shasta</h1><figure><img src=”/images/pets/shasta1.jpg” alt=”Shasta”><figcaption><p>Couch potato</figcaption></figure><nav id=”gallerynav”><p><a href=...

  • Page 403

    ptg999382HOUR 22: Controlling the Browser History with the History APIhref = “/photogallery/shasta1.html”;} else {href = “/photogallery/” + href.split(“/”).pop();}req = $.get(href, {},function() {$(“#photogallery”).html(req.responseText);buildLinks();return true;});return false;}T...

  • Page 404

    ptg999Dangers and Annoyances of the History API383You can see an example of this application at actionURI(www.html5in24hours.com/examples/history-api-examples-photogallery.html):www.html5in24hours.com/actionURI(www.html5in24hours.com/examples/history-api-examples-photogallery.html):examples/histo...

  • Page 405

    ptg999384HOUR 22: Controlling the Browser History with the History APIYou can see a simple example of this issue at my About.com site. I don’t conductany phishing, but I can change the URL of the page: actionURI(http://webdesign.about.com/library/bl-testing-history-api.htm):http://webdesign.abo...

  • Page 406

    ptg999Q&A385 12,Q&AQ.One of the reasons I use Ajax to build web applications is so that I don’t haveto create all the pages on the site. But it seems like you are saying I need tocreate the pages that I add to the history so that if someone bookmarksthem, they will be able to get to the...

  • Page 407

    ptg999386HOUR 22: Controlling the Browser History with the History API 12,WorkshopThe workshop contains quiz questions to help you process what you’ve learned inthis chapter. Try to answer all the questions before you read the answers. SeeAppendix A, “Answers to Quizzes,” for answers.Quiz1....

  • Page 408

    ptg999What Is Geolocation?387 12,HOUR 12,23 12,Adding Location Detection 12,with GeolocationWhat You’ll Learn in This Hour:. How to detect location data with the Geolocation API. How to handle privacy concerns with geolocation. How to use APIs to work with location dataGeolocation allows web ...

  • Page 409

    ptg999388HOUR 23: Adding Location Detection with GeolocationWhat’s important to note is that the API doesn’t care how that information isreceived. It doesn’t require that users have GPS-enabled devices, just that thebrowsers they are using can figure out a location in some fashion.The IP ad...

  • Page 410

    ptg999What Is Geolocation?389. Mapping—Maps and directions are the most common use. Geolocation letsyou pinpoint where users are and guide them exactly where they want to go.. Photo locator—Identifying photo locations is a useful feature. Manymobile devices and cameras include location data w...

  • Page 411

    ptg999390HOUR 23: Adding Location Detection with GeolocationMaking a call to either getCurrentPosition()or watchPosition()creates apositionobject. Eight properties are on the positionobject:. coords.latitude—The latitude of the position in decimal degrees. This willalways be on the object. coor...

  • Page 412

    ptg999What Is Geolocation?391To use the getCurrentPosition()method, you call it in a function with a callbackmethod for success and failure:function getLocation() {navigator.geolocation.getCurrentPosition(mapIt, locationError);}Then the success method (mapIt() in the preceding line) uses the posi...

  • Page 413

    ptg999392HOUR 23: Adding Location Detection with GeolocationUsing Other Location Data OptionsYou can set three other options with the getCurrentPosition()andwatchPosition()methods. These are placed in the third argument, thepositionOptionsobject, for these methods. The options are. enableHighAccu...

  • Page 414

    ptg999What Is Geolocation?393The maximumAgeproperty is useful for indicating how long location data will bevaluable to the application. This property helps speed up the application by onlyrequesting the information from the device when the maximum age limit is reached.So if you asked for data at ...

  • Page 415

    ptg999394HOUR 23: Adding Location Detection with Geolocation. Blackberry. Internet Explorer. Nokia. Opera Mobile. webOS. Windows Mobile. And othersTo use geo.js, you download geo.js and install both Google Gears and geo.js at thebottom of your document:<script src=”http://code.google.com/api...

  • Page 416

    ptg999Privacy and Geolocation395You Can Get Location Data in Other WaysIf you’ve visited the web lately, you have probably seen ads that are related towhere you live. These are not using geolocation to get your location, but ratheryour IP address. Many companies provide web developers access to...

  • Page 417

    ptg999396HOUR 23: Adding Location Detection with GeolocationDid youKnow?. The prompt is unconditional, and will appear every time the websiteattempts to use location services until the user chooses to share or not share.. The prompt blocks the API until it has an answer, so you cannot get loca-ti...

  • Page 418

    ptg999▼Creating a Mobile Geolocation Application397. Google Maps JavaScript API—Possibly the best-known maps API, theGoogle Maps JavaScript API lets you create solutions for both desktop andmobile devices actionURI(http://code.google.com/apis/maps/documentation/javascript/):(http://code.googl...

  • Page 419

    ptg999398HOUR 23: Adding Location Detection with Geolocation5.You should also include a section to display the map, the map options, and thetrigger to get the map:<section id=”getMapInfo”><h3>Map Options</h3><p>Zoom level:Orbit (1)<input id=”zoomLvl” value=”11...

  • Page 420

    ptg999Creating a Mobile Geolocation Application399break;case 3:alert(“Location services timed out”);break;default:alert(“Location could not be determined.”);}$(“#getMapInfo”).hide();$(“#supports”).append(“ There was an problem mapping your➥location, please try again later.”)...

  • Page 421

    ptg999400HOUR 23: Adding Location Detection with GeolocationFIGURE 23.2Safari getting alocation with theGeolocation API.Another easy way to add static maps based on location data to your site is to usethe MapQuest Open API for static maps. This option just uses an image with URLparameters.To set ...

  • Page 422

    ptg999Q&A401 12,SummaryThis hour taught you that location data can be collected by web browsers in manyways. Some, such as GPS tools inside smartphones, can be very accurate, whereasothers, such as IP address data mapping, can be inexact, showing the location ofthe IP address provider rather ...

  • Page 423

    ptg999402HOUR 23: Adding Location Detection with GeolocationWireless networks are getting more accurate with their location data becausethe network providers use tools from companies such as Skyhook actionURI(www.skyhookwireless.com/):(www.actionURI(www.skyhookwireless.com/):skyhookwireless.com/)...

  • Page 424

    ptg999Workshop403Exercises1.Convert the application you created in this hour to use geo.js as a fallbacksystem.2.Build an application that polls the location periodically and updates themap with the new location data.3.Visit one of the other map API sites and rebuild the application using itinste...

  • Page 425

    ptg999This page intentionally left blank actionURI(http://www.freepdf-books.com /):www.freepdf-books.com http://freepdf-books.com

  • Page 426

    ptg999Comparing the Difference Between Native and HTML5 Apps405 12,HOUR 12,24 12,Converting HTML5 Apps to 12,Native AppsWhat You’ll Learn in This Hour:. The difference between native and HTML5 applications. Advantages of native and HTML5 apps. How to convert HTML5 apps to native. How to creat...

  • Page 427

    ptg999406HOUR 24: Converting HTML5 Apps to Native Appsthose languages you gain access to device-specific options such as the camera orpush notifications.As a web designer or web developer, you already know HTML, CSS, and JavaScript.However, you need to learn Objective C or Java or both to write n...

  • Page 428

    ptg999Comparing the Difference Between Native and HTML5 Apps407. Access device files—Native apps can interact with files on the devices suchas photos and contacts, but these are hidden from HTML5 apps.. Better graphics than HTML5—HTML5 has Canvas, but it is not going to cre-ate a full 3D expe...

  • Page 429

    ptg999408HOUR 24: Converting HTML5 Apps to Native Appsstyle the app to look however you want. HTML5 apps can look like a webpage or an application, using the same code.. The functionality is coming—HTML5 may not have support for every fea-ture on a device, but it’s coming. More and more APIs ...

  • Page 430

    ptg999Converting to Native Apps409You can use a few tools to convert HTML5 apps to native apps. Two of the best-known are. PhoneGap actionURI(www.phonegap.com/):(www.phonegap.com/). Appcelerator actionURI(www.appcelerator.com/):(www.appcelerator.com/)Not All Devices Are Created EqualWhen you buil...

  • Page 431

    ptg999▼410HOUR 24: Converting HTML5 Apps to Native AppsBy theWayTo build Android applications you need a few more things:. Eclipse Classic IDE—This is a development environment that you’ll use tomanage your Android apps actionURI(www.eclipse.org/downloads/):(www.eclipse.org/downloads/).. An...

  • Page 432

    ptg999▼Converting to Native Apps411By theWay5.After your application is open in Xcode, right-click on the project name andchoose Show in Finder.6.Finder will show a folder called www. You need to drag that folder from Finderinto Xcode onto your project.7.Select Create Folder References for Any ...

  • Page 433

    ptg999412HOUR 24: Converting HTML5 Apps to Native Apps3.Select the ADT Plug-in at this actionURI(https://dl-ssl.google.com/android/eclipse/):URL: https://dl-ssl.google.com/android/eclipse/from the options.4.After installing the plug-in, open a new Android project from the File menu.You may have t...

  • Page 434

    ptg999Converting to Native Apps413WatchOut!<uses-permission➥android:name=”android.permission.MODIFY_AUDIO_SETTINGS” /><uses-permission android:name=”android.permission.READ_CONTACTS” /><uses-permission android:name=”android.permission.WRITE_CONTACTS” /><uses-per...

  • Page 435

    ptg999414HOUR 24: Converting HTML5 Apps to Native Apps 12,Creating Application 12,IconsOne feature that sets apart native applications from HTML5 apps is the icons thatare used to represent them. To get your HTML5 application ready for testing on adevice and then deploying to an app store, you n...

  • Page 436

    ptg999Creating Application Icons415Did youKnow?TABLE 24.1Apple Icon and Image SizesImageiPhone/iPod Touch (Pixels)iPhone 4 High resolution (Pixels)iPad (Pixels)Application icons57× 57114× 11472× 72App Store icon512× 512512× 512512× 512Launch image320× 480640× 960768× 1004 (Portrait)1024...

  • Page 437

    ptg999▼416HOUR 24: Converting HTML5 Apps to Native AppsAndroid has a couple of rules for launcher icons:. The icon must be modern, minimal, matte, tactile, and textured.. The icon must have a limited color palette and be forward-facing and top lit.Visit the Android Developers site for more info...

  • Page 438

    ptg999Testing Your Applications417FIGURE 24.1Testing theBirthday Listapplication onan iPad.1.Add your device to the provisioning portal by going to actionURI(http://developer.apple.com/ios/manage/devices/index.action):http://developer.apple.actionURI(http://developer.apple.com/ios/manage/devices/...

  • Page 439

    ptg999▼418HOUR 24: Converting HTML5 Apps to Native AppsTry It YourselfPutting Your Application on Your Android DeviceIn this Try It Yourself you use Eclipse to connect with your device and test yourapplication there. This example shows a trick you can use to get the application torun on the dev...

  • Page 440

    ptg999Summary419is available on the Android Developers site actionURI(http://developer.android.com/guide/publishing/app-signing.html#releasemode):(http://developer.android.com/guide/actionURI(http://developer.android.com/guide/publishing/app-signing.html#releasemode):publishing/app-signing.html#r...

  • Page 441

    ptg999420HOUR 24: Converting HTML5 Apps to Native Appshardware and software (camera, accelerometer, calendar, and contacts) more readilythan HTML5 apps. However, you also learned that most users can’t tell when theyare using an HTML5 app or a native app (even with the speed differences) in most...

  • Page 442

    ptg999Workshop421App Store, to send you their UDID. You can add their device to your devices inthe provisioning portal. Create a provisioning profile called Ad Hoc and addyour app to it. Finally, build the application for distribution in Xcode and sendit to your testers. They can use iTunes to in...

  • Page 443

    ptg999This page intentionally left blank actionURI(http://www.freepdf-books.com /):www.freepdf-books.com http://freepdf-books.com

  • Page 444

    ptg999Hour 1, “Improving Mobile Web Application Development with HTML5”423 13,APPENDIX 13,A 13,Answers to QuizzesThis appendix provides the answers to the quiz questions in each hour. 13,Hour 1, 13,“Improving Mobile Web 13,Application Development 13,with HTML5”1.HTML5 was started by a...

  • Page 445

    ptg999424APPENDIX A: Answers to Quizzes3.There are both new event attributes and global attributes that assist in dragand drop operations. The new event attributes are ondrag, ondragend,ondragenter, ondragleave, ondragstart, and ondrop. The new globalattributes are draggableand dropzone. 13,Hour ...

  • Page 446

    ptg999Hour 6, “Building a Mobile Web Application”425 13,Hour 5, 13,“JavaScript and HTML5 Web 13,Applications”1.True. The <script>tag is valid in both the head and body of your HTMLdocuments.2.The :linkand :hoverpseudoclasses allow you to set a style on a text linkand have that styl...

  • Page 447

    ptg999426APPENDIX A: Answers to Quizzes. Use mobile-specific functions.. Minimize perceived wait times.. Optimize images and use good contrasting colors.. Use ems or percentages for sizes.. Keep your content clear.. Beware of technology that may break.. Avoid technology that does break. 13,Hour 7...

  • Page 448

    ptg999Hour 10, “Drawing with the HTML5 Canvas Element”427a page. Smartphones and computer browsers can handle larger pages, butthe smaller they are the faster they load, so 30KB–50KB is still a good rangeto strive for.3.The five elements of design are color, direction, lines, shapes, and te...

  • Page 449

    ptg999428APPENDIX A: Answers to Quizzes4.A. The default style for line endings is butt.5.True. Circles are drawn on the <canvas>element using radians.6.True. You cannot set box model styles such as margin and padding on textdrawn on the <canvas>element.7.To draw an image file onto a c...

  • Page 450

    ptg999Hour 14, “Editing Content and User Interaction with HTML5”4295.The typeattribute has the format type=’MIME type; codecs=”videocodec, audio codec”’.6.Any content inside the <audio>element other than <source>and <track>is assumed to be fallback content. Browsers ...

  • Page 451

    ptg999430APPENDIX A: Answers to Quizzes 13,Hour 15, 13,“Microformats and Microdata”1.You can mark up almost anything that has a standard format with micro-data. Some examples mentioned in the book are events, contact informa-tion, recipes, reviews, resumes, and geography.2.The itempropattrib...

  • Page 452

    ptg999Hour 19, “WebSockets, Web Workers, and Files”4313.The image map element <area>now can use the attributes rel, media,and hreflangjust like the <a>element.4.Use the rel=nofollowattribute when you don’t endorse the link’s contentssuch as in comments or forum posts, on paid ...

  • Page 453

    ptg999432APPENDIX A: Answers to QuizzesIt sends messages back to the script:onmessage = function(e){if ( e.data === “start” ) {done()}};function done(){postMessage(“done”);}3.The easiest way is to add two attributes to your <input>element—multiple=trueand accept=”text/*”. Howe...

  • Page 454

    ptg999Hour 22, “Controlling the Browser History with the History API”433. Web storage can be specific to a window as well as to the browserand domain.2.Local storage is persistent and can be accessed even after the browser orcomputer has been shut down. Session storage is specific to the wind...

  • Page 455

    ptg999434APPENDIX A: Answers to Quizzes5.True. As long as your data does not exceed the limit of 640KB, you caninclude anything you want to include there.6.False. You can only change the URL to locations on the current domain. 14,Hour 23, 14,“Adding 14, Location 14, Detection 14,with Geolocati...

  • Page 456

    ptg999Hour 24, “Converting HTML5 Apps to Native Apps”4353.For developing iOS applications, you need a Macintosh computer andXcode. For developing Android applications, you need Eclipse Classic,Android SDK, and the ADT plug-in for Eclipse. You can build Android appswith just the SDK, but doing...

  • Page 457

    ptg999This page intentionally left blank actionURI(http://www.freepdf-books.com /):www.freepdf-books.com http://freepdf-books.com

  • Page 458

    ptg999[(H3F)]437 14,APPENDIX 14,B 14,HTML Elements and 14,AttributesHTML elements and attributes are the building blocks of a web application. Thisappendix will give you a brief explanation of them and indicate which ones arenew in HTML5. You should be aware that the HTML5 specification is stil...

  • Page 459

    ptg999438APPENDIX B: HTML Elements and AttributesTagExplanationBDOOverride control of the direction of textBLOCKQUOTELong quotationBODYBody of the pageBRLine breakBUTTONForm buttonBUTTON TYPE=BUTTONForm button with no semantic meaningBUTTON TYPE=RESETReset buttonBUTTON TYPE=SUBMITSubmit buttonCAN...

  • Page 460

    ptg999HTML5 Elements439TagExplanationFIELDSETGroup of related form controlsFIGCAPTIONFigure caption (new)FIGUREFigure with optional caption (new)FOOTERFooter (new)FORMFormH1First-level headingH2Second-level headingH3Third-level headingH4Fourth-level headingH5Fifth-level headingH6Sixth-level headi...

  • Page 461

    ptg999440APPENDIX B: HTML Elements and AttributesTagExplanationINPUT TYPE=HIDDENHidden form fieldINPUT TYPE=IMAGEImage input controlINPUT TYPE=MONTHYear and month input control (new)INPUT TYPE=NUMBERNumber input control (new)INPUT TYPE=PASSWORDPassword input controlINPUT TYPE=RADIORadio buttonINP...

  • Page 462

    ptg999HTML5 Elements441TagExplanationOBJECTGeneric external contentOLOrdered or numbered listOPTGROUPGroup of options in a select listOPTIONOption in a select listOUTPUTResult of a form calculation (new)PParagraphPARAMInitialization parameters of an OBJECTPREPre-formatted textPROGRESSProgress ind...

  • Page 463

    ptg999442APPENDIX B: HTML Elements and AttributesTagExplanationTBODYTable body rowsTDTable cellTEXTAREAMulti-line text input controlTFOOTTable footer rowsTHTable header cellTHEADTable heading rowsTIMEDate and/or time (new)TITLETitleTRTable rowTRACKSupplementary media track (new)UText normally sty...

  • Page 464

    ptg999HTML5 Attributes443AttributeExplanationContextmenuThe IDto associate with this element as a context menu.(new)DirThe direction of the text (ltr or rtlor auto).DraggableIndicates whether the element is draggable (true) or not(false). (new)dropzoneIndicates the types of content that can be dr...

  • Page 465

    ptg999444APPENDIX B: HTML Elements and AttributesAttributeExplanationondblclickUser clicked twice on or over the element.ondragUser is continuing to drag the element. (new)ondragendThe user stopped dragging. (new)ondragenterThe drag operation entered the element. (new)ondragleaveThe drag operatio...

  • Page 466

    ptg999HTML5 Attributes445AttributeExplanationonmousewheelUser rotated the mouse wheel.onpauseUser paused playback. (new)onplayUser started playback. (new)onplayingPlayback has started. (new)onprogressBrowser is fetching media data. (new)onratechangePlayback rate changed. (new)onreadystatechangeEl...

  • Page 467

    ptg999This page intentionally left blank actionURI(http://www.freepdf-books.com /):www.freepdf-books.com http://freepdf-books.com

  • Page 468

    ptg999Books447 14,APPENDIX 14,C 14,HTML5 and Mobile 14,Application ResourcesHow to use HTML5 and the related APIs is a lot to learn. Many books and websitesare available that you can use to learn more. 14,BooksThe following books can teach you a lot about HTML in general, and about some ofthe r...

  • Page 469

    ptg999448APPENDIX C: HTML5 and Mobile Application Resources. Programming the Mobile Web by Maximiliano Firtman. O’Reilly, 2010. ISBN978-0596807788. 14,WebsitesThe following websites will help you learn more about HTML5 and related APIs:. W3C actionURI(www.w3.org/):(www.w3.org/)—The W3C is whe...

  • Page 470

    ptg999A<a> tag, 47,26, 315,294block-level linking, 316,295-296changes to, 315,294-295link types, 321,300placeholder links, 317,296-297<abbr> tag, 48,27, 176,155about attribute, 290,269absolute positioning, 59,38accept attribute, 354,333accessibility validators, 142,121<ac...

  • Page 471

    ptg999Android SDK, 431,410Android tablets, 147,126animated URLs, 405,384APIsfor web applications, 331,310in HTML5, 50,29App Store icon, 435,414Appcelerator, 430,409Apple App store, submitting applications to, 439,418Apple icon, 436,415Apple iOS developer accounts, 437,416apple-mobile-we...

  • Page 472

    ptg999B<b> tag, 47,26, 176,155background colors, rotating, 335,314-315background images, adding, 114,93-94background property, 115,94background threads, 347,326-332background-color property, 115,94, 146,125background-image property, 115,94background-position property, 115,94background...

  • Page 473

    ptg999testing in, 28,7video codec support, 227,206-208web applications and, 25,4Web SQL Database API support, 382,361WebSockets API support, 344,323WOFF (Web Open FontFormat) support, 222,201-202Browsershots, 28,7, 85,64browsing contexts, 316,295business marks, 218,197Ccache manifest, 3...

  • Page 474

    ptg999<command> tag, 42,21, 258,237, 319,298commandsexecCommand() method com-mands, 268,247-251menu commands, 257,236-237comments, conditional, 78,57common fonts, 58,37communication, WebSockets API, 344,323benefits of, 345,324-325browser support, 344,323establishing, 346,325-326se...

  • Page 475

    ptg999on mobile devices, 67,46new features, 63,42rounded corners, 63,42-44shadows, 66,45transparent colors, 66,45curly quotes, 217,196custom fonts, 220,199-201custom video controls, creating, 238,217-219customers, planning web applications, 108,87Ddata storage. See web storagedata types, ...

  • Page 476

    ptg999dotMobi Emulator, 155,134downloading event, 368,347drag and dropattributes, 300,279-280browser support, 297,276-277building, steps for, 301,280-281CSS extensions, 301,280dataTransfer object, 304,283drag events, setting on draggable objects, 302,281draggable objects,defining, 302,28...

  • Page 477

    ptg999for mobile devices, 137,116offline web applications, 363,342on drop zones, setting, 303,282-283WebSockets API, 347,326execCommand() methodcommands supported by, 268,247-251disabling user interface, 268,247executeSql() method, 383,362explicit section of cache mani-fest, 365,344eXtensib...

  • Page 478

    ptg999<output> tag, 257,236placeholder text, 245,224-226validatingwith JavaScript, 92,71with jQuery, 97,76-78validation, 258,237-239<frame> tag, 48,27frames, lack of support for, 31,10<frameset> tag, 48,27frameworks for multiple devicesupport, 153,132-133fraud detection, g...

  • Page 479

    ptg999HTMLdeciding when to upgrade, 126,105-106browser support for stan-dards, 127,106-108browser usage, 130,109-110growth in mobile webbrowsing, 131,110-111iterative design, 129,108-109entities. See characterentitiesmobile web applications,building, 110,89-91storing data in,disadvantages of...

  • Page 480

    ptg999hyphenate-limit-lines property, 216,195hyphenate-limit-zone property, 216,195hyphenate-resource property, 216,195hyphenation, 214,193-195hyphens property, 216,195I<i> tag, 47,26, 176,155icon link type, 320,299icons, creating, 435,414-416id attribute, 39,18, 48,27, 316,295IE...

  • Page 481

    ptg999date pickers, 253,232as fallback for autocompleteand datalists, 249,228forms, validating, 97,76-78image rollovers, creating, 96,75-76web applications, advantagesof jQuery, 99,78-79jQuery Mobile, 100,79-81, 153,132jWebSocket, 346,325KKaazing HTML5 WebSocketGateway, 346,325<kbd>...

  • Page 482

    ptg999Mmanaging cookies withJavaScript, 92,71-72manifest attribute, 364,343<map> tag, 318,297mappinggeolocation, 410,389mapping application example, 418,397-400MapQuest Open API, 418,397maps, static, 421,400<mark> tag, 39,18, 135,114, 177,156-157market share for browsers, 71,5...

  • Page 483

    ptg999converting web applications tochanging the visualdesign, 145,124-130checking for HTML5 andCSS3 support, 151,130-132compatibility with olderbrowsers, 155,134-138evaluating the content, 144,123-124multiple device support, 153,132-133testing on multipledevices, 154,133-134testing the appli...

  • Page 484

    ptg999octagons, drawing, 193,172offline web applications, 136,115, 362,341-342browser support, 363,342cache manifest, 364,343lazy cache setup, 367,346-347usage of, 364,343-344writing, 365,344-346debugging application cache, 372,351-352DOM events and properties, 368,347-348events, 363,342l...

  • Page 485

    ptg999phones. See mobile devicesphoto gallery example, 401,380-383photo locator, 410,389phpwebsocket, 346,325picoformats, 293,272pingback link type, 320,299placeholder attribute, 245,224-226placeholder links, 317,296-297placeholder text, 135,114, 245,224-226planning mobile web applicatio...

  • Page 486

    ptg999<rt> tag, 44,23ruby annotations, support for, 134,113<ruby> tag, 44,23S<s> tag, 47,26, 176,155<samp> tag, 176,155sans serif fonts, serif fonts versus, 113,92saving gift status in online storeexample, 380,359-360Scalable Vector Graphics (SVG), 136,115scaling imag...

  • Page 487

    ptg999shadowsadding to text, 199,178-179creating, 66,45shapesclearing, 187,166drawing, 186,165-166circles, 196,175-177polygons and lines, 192,171-175rectangles and squares, 187,166-171in mobile designs, 148,127sidebars<aside> tag, 165,144-145sidebar link type, 320,299, 326,305simple...

  • Page 488

    ptg999source attributes, 235,214-215track attributes, 236,215video attributes, 234,213-214nesting, 24,3sectioning elements<article> tag, 165,144<aside> tag, 165,144-145building blog with, 173,152-154<h1> tag, 167,146heading, header, footerelements, 171,150-152list of, 162,1...

  • Page 489

    ptg999updateready event, 368,347upgradingdeciding when to upgrade, 126,105-106browser support for standards, 127,106-108browser usage, 130,109-110growth in mobile webbrowsing, 131,110-111iterative design, 129,108-109to HTML5adding features as extras, 134,113-115browser support for, 133,112-1...

  • Page 490

    ptg999converting to mobile applicationschanging the visualdesign, 145,124-130checking for HTML5 andCSS3 support, 151,130-132compatibility with olderbrowsers, 155,134-138evaluating the content, 144,123-124multiple device support, 153,132-133testing on multipledevices, 154,133-134testing the ap...

  • Page 491

    ptg999for HTML5 information, 469,448writing for mobile devices, 28,7content included, 29,8-9on separate domain, 31,10screen size/resolution, 29,8testing, 32,11validity and size of code, 30,9-10what to avoid, 30,9-10WebSockets API, 344,323benefits of, 345,324-325browser support, 344,323...

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 Mobile Books, Mobile Book Pdf, Mobile Pdf Books, Mobile Pdf Books Download, Mobile Pdf Books Free Download, Free ReadOnline Books, ReadOnline Book Pdf, ReadOnline Pdf Books, ReadOnline Pdf Books Download, ReadOnline Pdf Books Free Download,