Free Download PDF Books, Head First HTML5 Programming

Head First HTML5 Programming

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

Summary of Contents

  • Page 1

    A Brain-FriendlyGuideHead FirstHTML5ProgrammingA learner’s guidex*'to building web appswith JavaScript\rrLearn thesecrets oftheHTML5 guruLoadHTML5 andJavaScript straightinto your brainDiscover whyeverythingyour|W friends know'*about video isprobably wrongm. .r.mijjjÿVmAvoidembarrassingbrowsers...

  • Page 2

    actionURI(https://freepdf-books.com /):www.freepdf-books.com Head FirstHTML5 ProgrammingWeb Design & Development/HTMLWhatwill you learnfrom this book?“If you aspireto createmodern web apps onany platform, you needthe thorough introduc¬tionto keyHTML5features provided byHead FirstHTML5Pr...

  • Page 3

    Advance Praise for Head First HTML5 Programming“HTML5 is the “future of the web”. How many times have you heard that? If you really want to understand the family of technologies that make up HTML5, read this book! Head First HTML5 Programming is the definitive book on HTML5 for everyone fro...

  • Page 4

    Advance Praise for Head First HTML5 Programming“Straightforward, informative and entertaining, Head First HTML5 Programming is a must for anyone wanting to get started with HTML5 or just to refresh their skills. The Head First series helps me to keep my technical skills up to date allowing me t...

  • Page 5

    Praise for other books from Eric Freeman & Elisabeth Robson“This book’s admirable clarity, humor and substantial doses of clever make it the sort of book that helps even non-programmers think well about problem-solving.” — Cory Doctorow, co-editor of Boing Boing and author...

  • Page 6

    Other related books from O’ReillyHTML5 Up and RunningHTML5 CanvasHTML5: The Missing ManualHTML5 GeolocationHTML5 Graphics with SVG and CSS3HTML5 FormsHTML5 MediaOther books in O’Reilly’s Head First seriesHead First C#Head First JavaHead First Object-Oriented Analysis and Design (OOA&D)H...

  • Page 7

    Beijing • Cambridge • Kln • Sebastopol • TokyoEric Freeman Elisabeth RobsonHead First HTML5 ProgrammingWouldn’t it be dreamy if there was an HTML5 book that didn’t assume you knew what the DOM, events, and APIs were, all by page three? It’s probably just a fantasy...building...

  • Page 8

    Head First HTML5 Programmingby Eric Freeman and Elisabeth RobsonCopyright © 2011 Eric Freeman and Elisabeth Robson. All rights reserved.Printed in the United States of America.Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.O’Reilly Media books may be ...

  • Page 9

    To Steve Jobs, who hyped HTML5 to the point where this book should sell a zillion copies...And to Steve Jobs, because he’s our hero.actionURI(https://freepdf-books.com /):www.freepdf-books.com actionURI(https://freepdf-books.com /):https://freepdf-books.com

  • Page 10

    viiithe authorsAuthors of Head First HTML5 ProgrammingElisabeth is a software engineer, writer, and trainer. She has been passionate about technology since her days as a student at Yale University, where she earned a Masters of Science in Computer Science and designed a concurrent, visual program...

  • Page 11

    ixtable of contentsTable of Contents (Summary)Table of Contents (the real thing)Your brain on HTML5 Programming. Here you are trying to learn something, while here your brain is doing you a favor by making sure the learning doesn’t stick. Your brain’s thinking, “Better leave room for more...

  • Page 12

    xtable of contents1 37,Welcome to Webville getting to know HTML5 38,Upgrade to HTML5 TOD 38,AY! 38, 38,2 40,Introducing the 40,HTML5-o-Matic, update your 40,HTML now! 40, 40,4 43,You’re closer to HTML5 43,markup than you think 43, 43,7 47,HTML5 Exposed: Confessions 47,of 47, the newest ...

  • Page 13

    xitable of contents2 71,A Little Codeintroducing JavaScript and the DOM 72,The Way JavaScript W 72,orks 72, 72,36 73,What can you do with 73,JavaScript? 73, 73,37 74,Declaring a variable 74, 74,38 76,How to name your v 76,ariables 76, 76,40 79,Getting Expressive 79, 79,43 82,Doing things o...

  • Page 14

    xiitable of contents3 121,A Little Interactivityevents, handlers and all that jazz 122,Get ready for Web 122,ville Tunes 122, 122,86 123,Getting started... 123, 123,87 124,But nothing happens when 124,I click “Add Song” 124, 124,88 125,Handling Events 125, 125,89 126,Making a Plan... 12...

  • Page 15

    xiiitable of contents 150,Expanding your vocabulary 150, 150,114 151,How to add your o 151,wn functions 151, 151,115 152,How a function works 152, 152,116 157,Anatomy of 157, a Function 157, 157,121 159,Local and Global Variab 159,les 159, 159,123 160,Knowing the scope of 160, your local and...

  • Page 16

    xivtable of contents5 201,Geolocationmaking your html location aware 202,Location, Location, Location 202, 202,166 203,The Lat and Long 203,of 203, it... 203, 203,167 204,How the Geolocation API determines 204,your location 204, 204,168 208,Just where are you anywa 208,y? 208, 208,172 212,...

  • Page 17

    xvtable of contents6 249,Extroverted Appstalking to the web 250,Mighty Gumball wants a Web app 250, 250,214 252,A little more background on Mighty Gumball 252, 252,216 255,So how do we make 255,requests to web services? 255, 255,219 256,How to make a request 256,from JavaScript 256, 256,22...

  • Page 18

    xvitable of contents 318,Our new startup: 318,TweetShirt 318, 318,282 319,Checking out the “comps” 319, 319,283 322,How to get a canv 322,as into your web page 322, 322,286 324,How to see your can 324,vas 324, 324,288 326,Drawing on the Canvas 326, 326,290 331,Failing gracefully 331, 3...

  • Page 19

    xviitable of contents 386,Meet Webville TV 386, 386,350 387,Plug that set in and test it 387,out... 387, 387,351 389,How does the video 389,element work? 389, 389,353 390,Closely inspecting the 390,video attributes... 390, 390,354 392,What you need to kno 392,w about video f 392,ormats 392...

  • Page 20

    xviiitable of contents 450,How browser storage works (1995 - 2010) 450, 450,414 453,How HTML5 Web storage w 453,orks 453, 453,417 454,Note to self... 454, 454,418 460,Were Local Storage and the Array separated at 460,birth? 460, 460,424 465,Creating the interface 465, 465,429 466,Now let’...

  • Page 21

    xixtable of contents 509,Web Workersputting javascript to work10 Slow script—do you want to continue running it? If you’ve spent enough time with JavaScript or browsing the web you’ve probably seen the “slow script” message. And, with all those multicore processors sitting in your new ...

  • Page 22

    xxtable of contents 568,#1 Modernizr 568, 568,532 569,#2 Audio 569, 569,533 570,#3 jQuery 570, 570,534 22,#4 XHTML is dead, long 22,live XHTML 22, 22,536 573,#5 SVG 573, 573,537 574,#6 Offline web apps 574, 574,538 575,#7 Web sockets 575, 575,539 576,#8 More canvas API 576, 576,540 578,#...

  • Page 23

    you are here 4 xxithe introhow to use this bookIntroI can’t believe they put that in an HTML5 programming book!In this section, we answer the burning question: “So why DID they put that in an HTML5 book?”actionURI(https://freepdf-books.com /):www.freepdf-books.com actionURI(http://www....

  • Page 24

    xxii introhow to use this book12Who is this book for?Who should probably back away from this book?If you can answer “yes” to all of these:If you can answer “yes” to any of these:this book is for you.this book is not for you.[Note from marketing: this book is for anyone with a credit card...

  • Page 25

    you are here 4 xxiiithe introGreat. Only 640 more dull, dry, boring pages.We know what you’re thinking.And we know what your brain is thinking.“How can this be a serious HTML5 programming book?”“What’s with all the graphics?”“Can I actually learn it this way?”Your brain craves no...

  • Page 26

    xxiv introhow to use this bookSo what does it take to learn something? First, you have to get it, then make sure you don’t forget it. It’s not about pushing facts into your head. Based on the latest research in cognitive science, neurobiology, and educational psychology, learning takes a lot...

  • Page 27

    you are here 4 xxvthe introIf you really want to learn, and you want to learn more quickly and more deeply, pay attention to how you pay attention. Think about how you think. Learn how you learn.Most of us did not take courses on metacognition or learning theory when we were growing up. We were ...

  • Page 28

    xxvi introhow to use this bookHere’s what WE did:We used pictures, because your brain is tuned for visuals, not text. As far as your brain’s concerned, a picture really is worth a thousand words. And when text and pictures work together, we embedded the text in the pictures because your brai...

  • Page 29

    you are here 4 xxviithe introSo, we did our part. The rest is up to you. These tips are a starting point; listen to your brain and figure out what works for you and what doesn’t. Try new things.12345 Drink water. Lots of it.Your brain works best in a nice bath of fluid. Dehydration (which can ...

  • Page 30

    xxviii introhow to use this bookRead meThis is a learning experience, not a reference book. We deliberately stripped out everything that might get in the way of learning whatever it is we’re working on at that point in the book. And the first time through, you need to begin at the beginning, b...

  • Page 31

    you are here 4 xxixthe introTo write HTML5 and JavaScript code, you need a text editor, a browser, and, sometimes, a web server (it can be locally hosted on your personal desktop). The text editors we recommend for Windows are PSPad, TextPad or EditPlus (but you can use Notepad if you have to). ...

  • Page 32

    xxx introThe technical review teamthe review teamPaul BarryDavid PowersRebeca Duhn-KahnTrevor FarlowLou BarrBert BatesNo simple reviewer here, he’s also the series creator! Man, talk about pressure...Our Master Technical Reviewer.Our 110% effort reviewer. He even ran around in the middle of th...

  • Page 33

    you are here 4 xxxithe introAcknowledgmentsAt O’Reilly:Courtney Nash was given the difficult task managing not only the book Head First HTML5 Programming, but also managing, well, us. Courtney not only cleared all paths for us, but also applied the delicate pressure every editor needs to, to g...

  • Page 34

    xxxii introacknowledgmentsEven more Acknowledgments!And finally, thanks to Kathy and BertLast, and anything but least, to Kathy Sierra and Bert Bates, our partners in crime and the BRAINS who created the series. We hope, once again, we’ve done the series justice. Kathy SierraHard at work resea...

  • Page 35

    you are here 4 xxxiiithe introSafari® Books OnlineSafari® Books Online is an on-demand digital library that lets you easily search over 7,500 technology and creative reference books and videos to find the answers you need quickly.With a subscription, you can read any page and watch any video f...

  • Page 36

    actionURI(https://freepdf-books.com /):www.freepdf-books.com actionURI(https://freepdf-books.com /):https://freepdf-books.com

  • Page 37

    this is a new chapter 1We’re going to Webville! There’s so much great HTML5 construction going on, we’d be crazy to live anywhere else. Come on, follow us, and we’ll point out all the new sights on the way. getting to know html51Welcome to WebvilleHTML has been on a wild ride. Sure, HTML...

  • Page 38

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Head First Lounge</title> <...;

  • Page 39

    you are here 4 3getting to know HTML5After taking a careful look at the HTML on the page 2, can you see any markup that might change with HTML5? Or that you’d want to change? We’ll point out one for you: the doctype definition:Remember, the doctype definition belongs at the top of your HTML ...

  • Page 40

    4 Chapter 1update your htmlStep 1 is going to amaze you: follow along, we’re going to start at the top of the Head First Lounge HTML and update the doctype to give it that new HTML5 shine. Here’s the old HTML 4.01 version of the doctype:<!doctype html>No more Googling to remember what ...

  • Page 41

    you are here 4 5getting to know HTML5Congratulations, you’re now certified to upgrade any HTML to HTML5 !As a trained HTML5-o-Matic user, you’ve got the tools you need to take any valid HTML page and to update it to HTML5. Now it’s time to put your certification into practice!And, because ...

  • Page 42

    6 Chapter 1beyond markupWait a sec, all this fuss about HTML5 and this is all I needed to do? What is the rest of this book about?Okay, okay, you got us. So far, we’ve been talking about updating your older HTML pages so that they’re ready to take advantage of everything HTML5 has to offer. ...

  • Page 43

    you are here 4 7getting to know HTML5<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html> <head> <title>Head First Lounge</title> <meta http-equiv="content-type" content="tex...

  • Page 44

    8 Chapter 1exercise solutionHere’s the updated code:<!doctype html><html> <head> <title>Head First Lounge</title> <meta charset=“utf-8"> <link rel=“stylesheet" href=“lounge.css"> <script src=“lounge.js">&l...;

  • Page 45

    you are here 4 9getting to know HTML5Q: How does this work on the old browsers? Like the new doctype, meta, and so on... somehow the older browsers work with this new syntax?A: Yes, through a bit of cleverness and luck. Take the type attributes on the link and script tags; now, it makes sense to...

  • Page 46

    10 Chapter 1what you should knowWe don’t expect you to know HTML5, yet.If you’ve never had exposure to HTML5 before, that’s okay, but you should have worked with HTML, and there are some basics you should know about like elements, tags, attributes, nesting, the difference between semantic ...

  • Page 47

    you are here 4 11getting to know HTML5Head First: Welcome, HTML5. All the Web is buzzing about you. To us, you look a lot like HTML 4. Why is everyone so excited?HTML5: Everyone’s excited because I’m enabling a whole new generation of web applications and experiences.Head First: Right, but a...

  • Page 48

    12 Chapter 1the html5 landscapeWould the REAL HTML5 please stand up...HTML5 is all about multimedia, getting rid of plug-ins and using the new native support for audio and video.No, it’s all about more descriptive markup.Actually, it’s about rich Internet clients. Instead of building clients...

  • Page 49

    you are here 4 13getting to know HTML5The great thing about HTML5 is the client-side storage and caching functionality. Can you say offline access to the Web?I’m excited because I can use web workers to make my JavaScript more efficient and my page feel more responsive.There’s also a ton of ...

  • Page 50

    14 Chapter 1how html5 worksHow HTML5 really works...So we’ve said HTML5 is made up of a family of technologies, but what does that mean? Well you already know there’s the HTML markup itself, which has been expanded to include some new elements; there are also lots of additions to CSS with CS...

  • Page 51

    you are here 4 15getting to know HTML5Drag & DropOfflineCachingGeolocationVideoCanvasFormsWeb WorkersSocketsUsing JavaScript, you can interact with your page by manipulating the DOM, react to user or browser-generated events, or make use of all the new APIs.APIs, otherwise known as Applicat...

  • Page 52

    16 Chapter 1html5 family membersCanvasLocal StorageGeolocationOffline Web AppsNew MarkupCSS3We’re here to help with the structure and semantic meaning of your page, including new ways of making sections, headers, footers and navigation in your pages.FormsYou might have used me in HTML 4 to ent...

  • Page 53

    you are here 4 17getting to know HTML5Your mission......should you choose to accept it, is to do some reconnaissance on all the HTML browsers. We’re sure you’ve heard some browsers are ready for HTML5, and some aren’t. We need for you to get in close, because the truth is out there...YOUR...

  • Page 54

    18 Chapter 1browser reconnaissanceYOUR FIRST MISSION: BROWSER RECONNaISSaNCE SOLUTIONBrowservideoaudioCanvasWeb StorageGeolocationWeb WorkersOffline Web appsFirefoxSafariChromeMobile WebkitOperaIE 6, 7IE 8IE 9FeatureWe’ve cheated on our answers and filled them in for 2015. Yours should reflect...

  • Page 55

    you are here 4 19getting to know HTML5Wait a sec, if I start using HTML5 now, aren’t all those users of old browsers going to be alienated? Or, am I going to have to write two versions of my web page, one for browsers that support HTML5 and one for older browsers?Hold on, take a deep breath.Fi...

  • Page 56

    20 Chapter 1html5 common questionsQ: I heard that the HTML5 Standard isn’t going to be a final recommendation until 2022! Is that true? And, if so, why are we bothering?A: The W3C is the standards body that formally recommends the HTML5 standard, and what you need to know about the W3C is that...

  • Page 57

    you are here 4 21getting to know HTML5I’m just sayin’, if you’re going to get serious about building web apps and using HTML5, you’ve got to have JavaScript chops.We’ve gotta talk.If you’ve been with us since Head First HTML & CSS (or, you’ve read this far into the book without...

  • Page 58

    22 Chapter 1what javascript can doWhat can you do with JavaScript?JavaScript opens up a whole new universe of expression and functionality to your web pages. Let’s look at just a few things you might do with JavaScript and HTML5...With HTML5 & JavaScript you can create a 2D drawable surfa...

  • Page 59

    you are here 4 23getting to know HTML5You probably think we searched the Web far and wide to find the most exciting examples we could, right? Nope. All we did was take screenshots of the examples in the rest of this book. How’s that for cool? So now that you’re in Webville, it’s time to l...

  • Page 60

    24 Chapter 1getting to know javascriptHead First: Welcome, JavaScript. We’re glad you could work us into your busy schedule. Let me just put it out there: HTML5 is becoming quite a celebrity—what’s your take on this?JavaScript: I’m not someone who seeks the limelight, I’m a behind the ...

  • Page 61

    you are here 4 25getting to know HTML5Writing Serious JavaScript With all this talk about JavaScript, we bet you’re ready to jump in and see what it’s all about. They don’t call this Head First for nothing, we’ve got a super serious business application below that we’re going to throw ...

  • Page 62

    26 Chapter 1your first javascriptvar drink = "Energy Drink";Declare a variable, and assign it a value of “Energy Drink”.var lyrics = "";Declare another variable and assign it empty string value.var cans = 99;Declare another variable and assign it a number value, 99.while ...

  • Page 63

    you are here 4 27getting to know HTML5You didn’t think you’d do all that hard work on the exercise without giving JavaScript a try for real, did you? What you’ll need to do is take the code from the previous page and type it (along with the HTML below) into a file (like index.html), and th...

  • Page 64

    28 Chapter 1more html5 fine pointsQ: Why was there nothing in the body of that HTML except the script?A: We chose to start with an empty body because we created all the content for this page using JavaScript code. Now, sure, we could have just typed the song lyrics directly into the body element...

  • Page 65

    you are here 4 29getting to know HTML5We’ve talked about a bunch of things including HTML markup, JavaScript APIs, a “family of technologies” and CSS3. What exactly is HTML5? It can’t just be the markup everyone is so excited about...We’ll give you our unofficial answer:You see, when m...

  • Page 66

    30 Chapter 1what is html5, really++= Congratulations, you’ve finished Chapter 1 and written your first HTML5!Before you run off to the next chapter, we’ve got one more task for you to drive it all home. Use the magnets below to fill in the formula that solves the equation of “what...

  • Page 67

    you are here 4 31getting to know HTML5 ƒHTML5 is the newest version of HTML. It introduces simplified tags, new semantic and media elements, and relies on a set of JavaScript libraries that enable web applications. ƒXHTML is no longer the standard for web pages. Developers and the W3C decided ...

  • Page 68

    32 Chapter 1exercise solutionsHTML5crossIt’s time to give the right side of your brain a break and put that left side to work. All these words are HTML‑related and from this chapter. 12345678910111213141516Across2. __________ plug could also be called spam.8. Product that cleans up your HTML...

  • Page 69

    you are here 4 33getting to know HTML5CanvasLocal StorageGeolocationOffline Web AppsNew ElementsCSS3FormsAudio & VideoWeb WorkersSOlUTionWe’re here to help with the structure and semantic meaning of your page, including new ways of making sections, headers, footers and navigation in your p...

  • Page 70

    34 Chapter 1exercise solutionsHTML5cross SolutionD1S2H3A M E L E S4SG5OTCD6RJ7H8T9M L O M A TIC10R11E C O N N AIS S A N C E12YLSICCVLA13PIS4SPTEAEE11400TYFSM1PUCEW15HIL ELRNLITYPSX16H T M LAcross2. __________ plug could also be called spam. [SHAMELESS] 8. Product that cleans up your HTML5 is thr...

  • Page 71

    this is a new chapter 35Introducing JavaScript and the DOM2A Little CodeJavaScript is going to take you to new places. You already know all about HTML markup (otherwise known as structure) and you know all about CSS style (otherwise known as presentation), but what you’ve been missing is JavaS...

  • Page 72

    36 Chapter 2how javascript worksThe Way JavaScript WorksOur goal is to write JavaScript code that runs in the browser when your web page is loaded—that code might respond to user actions, update or change the page, communicate with web services, and in general make your page feel more like an ...

  • Page 73

    you are here 4 37javascript and the domWhat can you do with JavaScript?var temp = 98.6;var beanCounter = 4;var reallyCool = true;var motto = "I Rule";temp = (temp - 32) * 5 / 9;motto = motto + " and so do you!";var pos = Math.random();statementsloopingconditionalsOnce you’v...

  • Page 74

    38 Chapter 2declaring variablesDeclaring a variableVariables hold things. With JavaScript they can hold lots of different things. Let’s declare a few variables that hold things:var winners = 2;var boilingPt = 212.0;var name = "Dr. Evil";var isEligible = false;Integer numeric values.O...

  • Page 75

    you are here 4 39javascript and the domQ: What is the value of my variable when I just write: var winner;A: After this statement is executed, the variable winner will be assigned the value undefined, which is another JavaScript value and type. We’ll see where and how to use this later i...

  • Page 76

    40 Chapter 2naming variablesHow to name your variablesYou might be wondering how you pick names for your variables? If you’re used to naming ids in your HTML elements, you’ll find variables very similar. There are only a few rules for creating names:var thisIsNotaJoke;var _myvariable;var $im...

  • Page 77

    you are here 4 41javascript and the domRule #3: Make sure you avoid all of JavaScript’s reserved words.JavaScript contains a number of words that are reserved, such as if, else, while, and for (to name just a few), and JavaScript doesn’t take too kindly to you trying to use those reserved w...

  • Page 78

    42 Chapter 2naming variablesWebville Guide to Better NamingChoose names that mean something. Variable names like _m, r and foo might mean something to you but they are generally frowned upon in Webville. Not only are you likely to forget them over time, your code will be much more readable with ...

  • Page 79

    you are here 4 43javascript and the domGetting ExpressiveWe’ve already seen some JavaScript statements that look like:But let’s take a closer look at expressions, like the one in this statement. It turns out expressions are everywhere in JavaScript, so it’s important to know the kinds of t...

  • Page 80

    44 Chapter 2variable exercisesNot this kind of expression!Express Yourself!Based on what you know so far about JavaScript variables, expressions and statements, see if you can figure out which of these are legal and which might cause an error. From the following list, circle the statements that...

  • Page 81

    you are here 4 45javascript and the domEverything seems to work well if I add numbers to numbers or strings to strings, but what if I add a number to a string? Or an integer to a floating point number?Remember when we said JavaScript makes programming easy to get into? One of the ways it does th...

  • Page 82

    46 Chapter 2javascript iterationDoing things over and over...If we did everything just once in a JavaScript program it would probably be a pretty boring program. You do a lot of things multiple times—you rinse, lather, repeat, until hair is clean, or, keep driving until you reach your destinat...

  • Page 83

    you are here 4 47javascript and the domSo if you think about the while loop, we’re initializing some values, say, the number of ice cream scoops left, which the while loop tests, and if true, we execute a block of code. And, the block of code does some work that at some point updates the value...

  • Page 84

    48 Chapter 2variable and iteration exerciseBE the BrowserEach of the JavaScript snippets on this page is a separate piece of code. Your job is to play browser, and evaluate each snippet of code and answer a question about the result. Write your answer to the question below the code.var tops = 5;...

  • Page 85

    you are here 4 49javascript and the domWe’ve been using boolean expressions in for and while statements as a conditional test to decide whether to continue looping. You can also use them to make decisions in JavaScript. Here’s an example:if (scoops < 3) { alert("Ice cream is runnin...

  • Page 86

    50 Chapter 2javascript conditionalsYou can provide a catchall for your if statements as well—a final else that is run if all the other conditions fail. Let’s add a few more if/elses and also a catchall:Making more decisions... and, adding a catchallif (scoops == 3) { alert("Ice cream ...

  • Page 87

    you are here 4 51javascript and the domvar word1 = "a";var word2 = "nam";var word3 = "nal p";var word4 = "lan a c";var word5 = "a man a p";var phrase = "";for (var i = 0; ______; _____) { if (i == 0) { phrase = _______________...

  • Page 88

    52 Chapter 2how to put javascript in a pageI was told we’d be putting JavaScript in our web pages. When are we going to get there, or are we just going to keep playing around with JavaScript?Yes, that is the point. First, you needed to know a few basics. Here’s what we’ve done so far: you...

  • Page 89

    you are here 4 53javascript and the domHTML file<head><body><script> statement statement </script><script> statement </script><script src=”mycode.js”></script>How and where to add JavaScript to your pagesPlace your script inline, in the &l...;

  • Page 90

    54 Chapter 2interaction with a pageJavaScript and HTML are two different things. HTML is markup and JavaScript is code. So how do you get JavaScript to interact with the markup in your page? You use the Document Object Model. How JavaScript interacts with your pageIt’s through reading, reacti...

  • Page 91

    you are here 4 55javascript and the domIngredientsOne well‑formed HTML5 pageOne or more web browsersInstructions1. Start by creating a document node at the top.2. Next, take the top level element of your HTML page, in our case the <html> element, call it the current element and add it ...

  • Page 92

    56 Chapter 2introducing the document object modeldocument is always at the top. document is a special part of the tree that you can use in JavaScript to get access to the entire DOM. These are like the branches of the tree.These are like the leaves of the tree (because there are no elements insi...

  • Page 93

    you are here 4 57javascript and the dom<!doctype html><html lang="en"> <head> <title>Movies</title> </head> <body> <h1>Movie Showtimes</h1> <h2 id="movie1" >Plan 9 from Outer Space</h2> <p>...

  • Page 94

    58 Chapter 2relationship between javascript and the domOr, how two totally different technologies hooked up.HTML and JavaScript are from different planets for sure. The proof? HTML’s DNA is made of declarative markup that allows you to describe a set of nested elements that make up your pages....

  • Page 95

    you are here 4 59javascript and the domLet’s start with a DOM. Here’s a simple DOM; it’s got a few HTML paragraphs, each with an id identifying it as the green, red or blue planet. Each paragraph has some text as well. Of course there’s a <head> element too, but we’ve left the d...

  • Page 96

    60 Chapter 2using getelementbyidOnce getElementById gives you an element, you’re ready do something with it (like change its text to “Red Alert: hit by phaser fire!”). To do that, we typically assign the element to a variable so we can refer to the element thoughout our code; let’s do ...

  • Page 97

    you are here 4 61javascript and the domHere’s a DOM with a secret message hidden in it. Evaluate the code below to reveal the secret! The answer is upside down on this page.document.getElementById("e7")document.getElementById("e8")document.getElementById("e16")doc...

  • Page 98

    62 Chapter 2testing the dom code<!doctype html><html lang="en"><head> <title>Planets</title> <meta charset="utf-8"> <script> var planet = document.getElementById("greenplanet"); planet.innerHTML = "Red alert: h...

  • Page 99

    you are here 4 63javascript and the domOh yeah, we forgot to mention one thing.Most of the time it makes sense to start executing your JavaScript code after the page is fully loaded. The reason? Well, if you don’t wait until the page has loaded, then the DOM won’t be fully created when your ...

  • Page 100

    64 Chapter 2waiting for the page to load<script>function init() { var planet = document.getElementById("greenplanet"); planet.innerHTML = "Red alert: hit by phaser fire!";}window.onload = init;</script>You can’t mess with the DOM until the page has fully l...

  • Page 101

    you are here 4 65javascript and the dom<!doctype html><html lang="en"><head> <title>My Playlist</title> <meta charset="utf-8"> <script> ____________ addSongs() { var song1 = document.______________("________"); var...

  • Page 102

    66 Chapter 2more dom functionalityLook up and retrieve one or more elements from the DOM.So, what else is a DOM good for anyway?The DOM can do a fair bit more than we’ve seen so far and we’ll be using a lot of its other functionality as we move forward in the book, but for now let’s just t...

  • Page 103

    you are here 4 67javascript and the domCan we talk about JavaScript again? Or, how to store multiple values in JavaScriptYou’ve been hanging right in there with JavaScript and the DOM, and before we let you get some rest and relaxation, we wanted to tell you about one more JavaScript type that...

  • Page 104

    68 Chapter 2using an arrayAdding another item to the arrayAt any time you can keep adding new items to your array simply by using the next, unused index, like this:tempByHour[5] = 61;012345And now that we know how to get length of an array, let’s see if we can combine what you know about loops...

  • Page 105

    you are here 4 69javascript and the dom<!doctype html><html lang="en"><head><title>Temperatures</title><meta charset="utf-8"><script>function showTemps() { var tempByHour = new ____________; tempByHour[0] = 59.2; tempByHour[1...

  • Page 106

    70 Chapter 2phrase-o-matic example<!doctype html><html lang="en"><head> <title>Phrase-o-matic</title><meta charset="utf-8"><style>body { font-family: verdana, Helvetica, sans-serif;}</style><script>function makePhras...

  • Page 107

    you are here 4 71javascript and the domfunction makePhrases() {}window.onload = makePhrases;The Phrase-O-MaticWe hope you figured out this code is the perfect tool for creating your next start-up marketing slogan. It has created winners like “Win-win value-added solution” and “24/7 empowe...

  • Page 108

    72 Chapter 2how phrase-o-matic worksWe’re almost done, we have the phrase, now we just have to display it. By now you already know the drill: we’re going to use getElementById to locate our paragraph element and then use its innerHTML to put the new phrase there.var phraseElement = document....

  • Page 109

    you are here 4 73javascript and the domOkay, finish that last line of code, have one more look over it all and feel that sense of accomplishment before you load it into your browser. Give it a test drive and enjoy the phrases.6Just reload the page for endless start-up possibilities (okay, not en...

  • Page 110

    74 Chapter 2Learning a language is hard work and it requires you not only work your brain, but that you also rest your brain. So after this chapter take some well needed downtime, have a treat on us, but before you go, check out the bullet points and do the crossword to make things really stick....

  • Page 111

    you are here 4 75javascript and the dom ƒDeclare a JavaScript variable using var. ƒNumber, boolean and string are primitive types. ƒBoolean values are true and false. ƒNumbers can be integers or floating point numbers. ƒAn unassigned variable has the value undefined. ƒUndefined and null a...

  • Page 112

    76 Chapter 2crossword exerciseHTML5CrossTime to work a different part of your brain with a crossword. Have fun!12345678910111213141516171819Across2. 5 < 10 is a _________ expression.7. You can add your JavaScript to the ________ or body of your HTML.8. ____________ is the root of the DOM tre...

  • Page 113

    you are here 4 77javascript and the domBased on what you know so far about JavaScript variables, expressions and statements, see if you can figure out which of these are legal and which might cause an error. From the following list, circle the statements that are legal.var x = 1138;var y = 3/8;...

  • Page 114

    78 Chapter 2exercise solutions1015510BE the Browser SolutionEach of the JavaScript snippets on this page is a separate piece of code. Your job is to play browser, and evaluate each snippet of code and answer a question about the result. Write your answer to the question below the code.var tops =...

  • Page 115

    you are here 4 79javascript and the domvar scoops = 10;while (scoops >= 0) { if (scoops == 3) { alert("Ice cream is running low!"); } else if (scoops > 9) { alert("Eat faster, the ice cream is going to melt!"); } else if (scoops == 2) { ale...

  • Page 116

    80 Chapter 2exercise solutionsvar word1 = "a";var word2 = "nam";var word3 = "nal p";var word4 = "lan a c";var word5 = "a man a p";var phrase = "";for (var i = 0; __________; __________) { if (i == 0) { phrase = _______________...

  • Page 117

    you are here 4 81javascript and the domYour job is the act like you’re the browser. You need to parse the HTML and build your very own DOM from it. Go ahead and parse the HTML to the right, and draw your DOM below. We’ve already started it for you.Here’s our DOMdocumenthtmlheadtitlebody...

  • Page 118

    82 Chapter 2exercise solutions<!doctype html><html lang="en"><head> <title>My Playlist</title> <meta charset="utf-8"> <script> ____________ addSongs() { var song1 = document.______________("________"); var _____ = ...

  • Page 119

    you are here 4 83javascript and the dom<!doctype html><html lang="en"><head><title>Temperatures</title><meta charset="utf-8"><script>function showTemps() { var tempByHour = new ____________; tempByHour[0] = 59.2; tempByHour[1...

  • Page 120

    84 Chapter 2exercise solutionsHTML5Cross SolutionB1B2O O3L E A NG4OBJ5S6ROJH7E A DD8O C U M E N TL9E T T E RVREECM10A R K U PII11N D E XATSPPNC12A M E LC13O N V E R TLE14ORA15R R A YLDW16HIL ENSEPL17E N G T HG18E T E L E M E N T B YI D19TIOFMAcross2. 5 < 10 is a _________ expression. [BOOLEAN...

  • Page 121

    this is a new chapter 85events, handlers and all that jazz3A Little InteractionSure, he looks great, but this relationship would be so much more fun if he’d actually do something now and then.You still haven’t reached out to touch your user. You’ve learned the basics of JavaScript but can ...

  • Page 122

    86 Chapter 3introducing webville tunesGet ready for Webville TunesOkay, we’ve dragged you through a lot of JavaScript fundamentals so far in this book, and while we’ve talked a good game on building web apps, we don’t have a lot to show for it, yet. So, now we’re going to get serious (no...

  • Page 123

    you are here 4 87events and handlers<!doctype html><html lang="en"><head> <title>Webville Tunes</title> <meta charset="utf-8"> <script src="playlist.js"></script> <link rel="stylesheet" href="play...

  • Page 124

    88 Chapter 3about button click events““Well, yes and no. Nothing appears to happen, but your browser knows you clicked on the button (depending on your browser, you will also see the button depress). The real question is how do we get the button to do something when you click on it? And wha...

  • Page 125

    you are here 4 89events and handlersGreat, you’ll be the first to know in the event that happens.You’re going to see that many things are happening in the browser while your page is being displayed—buttons are being clicked, additional data your code requested from the network may be arriv...

  • Page 126

    90 Chapter 3coding the button handlerfunction handleButtonClick() { alert("Button was clicked!");}Making a Plan...Getting access to the “Add Song” button1. Set up a handler to handle the user’s click on the “Add Song” button.2. Write the handler to get the song name the us...

  • Page 127

    you are here 4 91events and handlersGiving the button a click handlerwindow.onload = init;function init() { var button = document.getElementById("addButton"); button.onclick = handleButtonClick;}function handleButtonClick() { alert("Button was clicked!");}Okay, we’...

  • Page 128

    92 Chapter 3how add song worksfunction init() { var button = document.getElementById("addButton"); button.onclick = handleButtonClick;}function handleButtonClick() { alert("Button was clicked!");}Don’t worry, if and when I’m clicked on, you’ll literally be the ...

  • Page 129

    you are here 4 93events and handlersfunction handleButtonClick() { alert("Button was clicked!");}Yes! Somone clicked on the button. I get to run the handleButtonClick function.Come on... click the button... just do it...3With the code written, the page is loaded and displayed by the...

  • Page 130

    94 Chapter 3getting the song from the domGetting the song nameHere’s the body part of the DOM.Using the getElementById method, we can get a handle to the songTextInput input element in the form.bodyul id=”playlist”forminput id=”addButton”input id=”songTextInput” value=”Blue Sued...

  • Page 131

    you are here 4 95events and handlersBONUSWhat if you wanted to test to make sure the user actually entered some text before clicking the button? How might you do that? (Again, find the solution on page 96.)Q: What is the value of the value property of the text input if the user didn’t type any...

  • Page 132

    96 Chapter 3exercise solutionsfunction handleButtonClick() { var textInput = document.getElementById("songTextInput"); var songName = textInput.value; alert("adding " + songName);}Rework the handleButtonClick function below to obtain the name of the song the user h...

  • Page 133

    you are here 4 97events and handlersWe’ve already got a lot working! You can type a song name into a form, click the Add Song button and get the text you typed into the form, all within your code. Now we’re going to display the playlist on the page itself. Here’s what it’s going to look ...

  • Page 134

    98 Chapter 3creating new elementsFor the playlist shown here, draw the DOM as it looks after you’ve added all these songs. Notice the order in which the songs are added to the page, and make sure the elements are in the right places in the DOM too. We’ve gone ahead and done one for you. Chec...

  • Page 135

    you are here 4 99events and handlersHow to create a new elementYou’ve already seen how to get access to existing elements through the DOM. But you can also use the DOM to create new elements (and then as a second step, add them to the DOM, which we’ll get to in a sec).Let’s say we want to ...

  • Page 136

    100 Chapter 3adding new elementsAdding an element to the DOMTo add a new element to the DOM you have to know where you want to put it. Well, we do know where to put it: we’re going to put the <li> element in the <ul> element. But how do we do that? Let’s take another look at the ...

  • Page 137

    you are here 4 101events and handlersfunction handleButtonClick() { var textInput = document.getElementById("songTextInput"); var songName = textInput.value; var li = document.createElement("li"); li.innerHTML = songName; var ul = document.getElementById("...

  • Page 138

    102 Chapter 3review of the playlist app1The first thing you did was set up an event handler to handle the user’s click on the “Add Song” button. You created a function, handleButtonClick, and set the onclick property of the “Add Song” button to this function.You did a lot in this chapt...

  • Page 139

    you are here 4 103events and handlersWait a sec, I get we’re interacting with the DOM and all, but how is this a real web App? If I close my browser, all my songs are gone. Shouldn’t my playlist items stick around if this is really an application?We agree, the playlist should be persistent;a...

  • Page 140

    104 Chapter 3Ready Bake CodeWe’ve gone ahead and baked a little code for you to save your playlists. For now you just need to type it in and make two tiny changes to your existing code and you’ll have an HTML5-stored playlist.We’ll be covering all the specifics of storing things locally in...

  • Page 141

    you are here 4 105events and handlersfunction save(item) { var playlistarray = getStorearray("playlist"); playlistarray.push(item); localStorage.setItem("playlist", JSON.stringify(playlistarray));}function loadPlaylist() { var playlistarray = getSavedSongs(); v...

  • Page 142

    106 Chapter 3storing the playlistfunction init() { var button = document.getElementById("addButton"); button.onclick = handleButtonClick; loadPlaylist();} function handleButtonClick() { var textInput = document.getElementById("songTextInput"); var songName = te...

  • Page 143

    you are here 4 107events and handlersThis is cool, we’re really starting to make the code and the page interact with each other. I’m curious though about functions, objects, and things like element.appendChild(). Do I need to learn more about those things?Perfect timing.We really wanted to ...

  • Page 144

    108 Chapter 3review of event handlers and the dom ƒThere are lots of events happening in your browser all the time. If you want to respond to these events, you need to handle the events with event handlers. ƒA button click event is triggered when you click on a button in a web page. ƒYou han...

  • Page 145

    you are here 4 109events and handlersHTML5crossGive yourself some time to understand the interactions between HTML and JavaScript. Think through how it all works together. While you’re doing that mix it up a little by doing this crossword. All the words are from this chapter. 12345678910Across...

  • Page 146

    110 Chapter 3exercise solutionsFor the playlist shown here, draw the DOM as it looks after you’ve added all these songs. Notice the order in which the songs are added to the page, and make sure the elements are in the right places in the DOM too. Here’s our solution.Here’s the rest of the ...

  • Page 147

    you are here 4 111events and handlersH1AC2R E A T E E L E M E N THDIA3P P E4N D C HIL DLLEDE5V E N TT6R E EISD7O8C U M E N TE9M P T YBVAJEGENECTL10O C A L S T O R A G EYSAcross2. DOM’s method for creating new elements. [CREATEELEMENT] 3. DOM’s method for adding new elements. [APPENDCHILD] 5....

  • Page 148

    actionURI(https://freepdf-books.com /):www.freepdf-books.com actionURI(https://freepdf-books.com /):https://freepdf-books.com

  • Page 149

    this is a new chapter 113javascript functions and objects4Serious JavaScriptCan you call yourself a scripter yet? Probably—you already know your way around a lot of JavaScript. But who wants to be a scripter when you can be a programmer? It’s time to get serious and take it up a notch—it�...

  • Page 150

    114 Chapter 4defining your own functions<script> var guessInput = document.getElementById("guess"); var guess = guessInput.value; var answer = null; var answers = [ "red", "green", "blue"]; var index = Math.fl...

  • Page 151

    you are here 4 115javascript functions and objectsHow to add your own functionsvar guessInput = document.getElementById("guess");var guess = guessInput.value;var answer = checkGuess(guess);alert(answer);You’ve been using built-in functions, like alert, or even Math.random, but what i...

  • Page 152

    116 Chapter 4how functions workHow a function worksfunction bark(dogName, dogWeight) { if (dogWeight <= 10) { return dogName + " says Yip"; } else { return dogName + " says Woof"; }}Okay, first we need a function.Let’s say you’ve just written your ne...

  • Page 153

    you are here 4 117javascript functions and objectsOptionally, we can have return statements in the body...... and that’s where we return a value back to the code that makes the call. Let’s see how that works:var sound = bark("Fido", 50);alert(sound);function bark(dogName, dogWeight...

  • Page 154

    118 Chapter 4importance of functions and objectsI keep tellin’ you, all of the HTML5 APIs are chock-full of functions, objects and all that advanced JavaScript stuff...If we could have another moment to talk...We know, we know, by Chapter 4 you thought you’d be flying in an HTML5 jetpack by...

  • Page 155

    you are here 4 119javascript functions and objectsHead First: Welcome Function! We’re looking forward to digging in and finding out what you’re all about.Function: Glad to be here.Head First: Now we’ve noticed many people who are new to JavaScript don’t tend to use you a lot. They just ...

  • Page 156

    120 Chapter 4parameters and argumentsI’m not sure I get the difference between a parameter and an argument—are they just two names for the same thing?No, they’re different.When you define a function you can define it with one or more parameters. function cook(degrees, mode, duration) { /...

  • Page 157

    you are here 4 121javascript functions and objectsNow that you know how to define and call a function, let’s make sure we’ve got the syntax down cold. Here are all the parts of a function’s anatomy:Anatomy of a Functionfunction addScore ( level , score ) { var bonus = level * score * .1...

  • Page 158

    122 Chapter 4exercise on parametersUse your knowledge of functions and passing arguments to parameters to evaluate the code below. After you’ve traced through the code, write the value of each variable below. Check your answers with the solution at the end of the chapter before you go on.funct...

  • Page 159

    you are here 4 123javascript functions and objectsLocal and Global VariablesYou already know that you can declare a variable by using the var keyword and a name anywhere in your script:function getScore(points) { var score; for (var i = 0; i < levelThreshold; i++) { //code here ...

  • Page 160

    124 Chapter 4local and global scopevar avatar = "generic";var skill = 1.0;var pointsPerLevel = 1000;var userPoints = 2008;function getavatar(points) { var level = points / pointsPerLevel; if (level == 0) { return "Teddy bear"; } else if (level == 1) { ret...

  • Page 161

    you are here 4 125javascript functions and objectsThe short lives of variablesI could have sworn the variable was right behind me, but when I turned around he was just...gone...When you’re a variable, you work hard and life can be short. That is, unless you’re a global variable, but even wit...

  • Page 162

    126 Chapter 4shadowing variablesYou “shadow” your global.Here’s what that means: say you have a global variable beanCounter and you then declare a function, like this:When you do this, any references to beanCounter within the function refer to the local variable and not the global. So we s...

  • Page 163

    you are here 4 127javascript functions and objectsIf this were a book on in-depth JavaScript programming we’d take you further into this topic, but given that this is Head First HTML5 Programming, we’ll just suggest you explore this topic further to improve the quality of your code! Q: Keepi...

  • Page 164

    128 Chapter 4functions as valuesfunction addOne(num) { return num + 1;}var plusOne = addOne;var result = plusOne(1);Oh, did we mention functions are also values?OK, you’ve used variables to store numbers, boolean values, strings, arrays, all kinds of things, but did we mention you can also ...

  • Page 165

    you are here 4 129javascript functions and objectsTake a look at this code: what do you think is going on?function init() { alert("you rule!");}window.onload = init;var element = document.getElementById("button");element.onclick = function () { alert("clicked!")...

  • Page 166

    130 Chapter 4pep talk before introducing objectsAuthors? Hello? Hello? I'm the girl who bought the HTML5 book, remember me? What does all this have to do with HTML5???Well we thought we’d covered that already... but if it looks like we’ve picked you up and have driven you halfway around the ...

  • Page 167

    you are here 4 131javascript functions and objectsWith objects, the future’s so bright we really DO have to wear shades...Did someone say “Objects”?!Ah, our favorite topic! Objects are going to take your JavaScript programming skills to the next level—they’re the key to managing comple...

  • Page 168

    132 Chapter 4objects and propertiesvar fido = { name: "Fido", weight: 40, breed: "Mixed", loves: ["walks", "fetching balls"]};Dogname: “Fido”weight: 40breed: “Mixed”loves: [“walks”, “fetching balls”]And a set of properties...W...

  • Page 169

    you are here 4 133javascript functions and objectsSome things you can do with objectsif (fido.weight > 25) { alert("WOOF");} else { alert("yip");}Access object properties with “dot” notation:Access properties using a string with [] notation:Enumerate all an object�...

  • Page 170

    134 Chapter 4what objects can doThe Dot Operator .The dot operator (.) gives you access to an object’s properties. In general it’s easier to read than the [“string”] notation: ● fido.weight is the size of fido. ● fido.breed is the breed of fido. ● fido.name is the name of fido. �...

  • Page 171

    you are here 4 135javascript functions and objectsCan we add properties to objects after we’ve defined them? Yes, you can add or delete properties at any time.To add a property to an object you simply assign a new property a value, like this:and from that point on fido will have a new property...

  • Page 172

    136 Chapter 4objects as argumentsLet’s talk about passing objects to functionsWe’ve already talked a bit about how arguments are passed to functions—arguments are passed by value, so if we pass an integer, the corresponding function parameter gets a copy of the value of that integer for it...

  • Page 173

    you are here 4 137javascript functions and objectsfido.weight = 48; ...loseWeight(fido);Dogname: “Fido”weight: 48breed: “Mixed”loves: [“walks”, “fetching balls”]fido is a reference to an object, which means the object doesn’t live in the fido variable, but is pointed to by the ...

  • Page 174

    138 Chapter 4introducing webville cinema appThe Webville Cinema has come to us for help with their JavaScript API; let’s start simple and design the movie object for them. What we need is a couple of movie objects that each include a title, a genre, a movie rating (1-5 stars) and a set of show...

  • Page 175

    you are here 4 139javascript functions and objectsvar movie1 = { title: "Plan 9 from Outer Space", genre: "Cult Classic", rating: 5, showtimes: ["3:00pm", "7:00pm", "11:00pm"]};var movie2 = { title: "Forbidden Planet", ...

  • Page 176

    140 Chapter 4implementing next showingfunction getNextShowing(movie) { var now = new Date().getTime(); for (var i = 0; i < movie.showtimes.length; i++) { var showtime = getTimeFromString(movie.showtimes[i]); if ((showtime - now) > 0) { return "Next showi...

  • Page 177

    you are here 4 141javascript functions and objectsGet the code on the previous page typed in and let’s give it a test run. You’ll see that the getNextShowing function takes whatever movie it is handed and figures out the next showing time. Feel free to create some new movie objects of your ...

  • Page 178

    142 Chapter 4objects and methodsObjects can have behavior too...You didn’t think objects were just for storing numbers, strings and arrays did you? Objects are active, they can do things. Dogs don’t just sit there: they bark, run, play catch and a dog object should too! Given everything you�...

  • Page 179

    you are here 4 143javascript functions and objectsvar movie1 = { title: "Plan 9 from Outer Space", genre: "Cult Classic", rating: 5, showtimes: ["3:00pm", "7:00pm", "11:00pm"], getNextShowing: function(movie) { var now = new ...

  • Page 180

    144 Chapter 4reworking a function as a methodWe’ve taken the liberty of removing the movie parameter, and all the references to it. Which leaves us with this code:Let’s get the movie parameter out of there...var movie1 = { title: "Plan 9 from Outer Space", genre: "Cult C...

  • Page 181

    you are here 4 145javascript functions and objectsLet’s add this each place we specify a property, so that we’re telling JavaScript we want the property in this object:Adding the “this” keywordvar movie1 = { title: "Plan 9 from Outer Space", genre: "Cult Classic"...;

  • Page 182

    146 Chapter 4code reuse and methodsAh, good eye.You have great instincts if you recognized that we are duplicating code when we copy getNextShowing into more than one movie object. One of the aims of “object-oriented” programming is to maximize code reuse—here we’re not reusing any code,...

  • Page 183

    you are here 4 147javascript functions and objectsHow to create a constructorLet’s make a constructor for dogs. We already know what we want our dog objects to look like: they have name, breed and weight properties, and they have a bark method. So what our constructor needs to do is take the p...

  • Page 184

    148 Chapter 4using a constructorDon’t worry about building all those objects yourself; we’ll construct them for you.Now let’s use our constructorNow that we’ve got our factory built, we can use it to create some dogs. There’s only one thing we haven’t told you, which is that you nee...

  • Page 185

    you are here 4 149javascript functions and objectsHow does this really work?Anytime we put this in the code of a method it will be interpreted as a reference to the object the method was called on. So, if we call fido.bark, then this is going to reference fido. Or, if we call it on our dog objec...

  • Page 186

    150 Chapter 4a movie constructorfunction _____________(_________, __________, rating, showtimes) { this.title = _________; this.genre = genre; this.________________ = rating; this.showtimes = ________________; this.getNextShowing = function() { var now = new Date().getTime(...

  • Page 187

    you are here 4 151javascript functions and objects Q: What’s the real difference between a function and a method? After all, if they’re the same thing why call them something different?A: By convention, if an object has a function we call that a method. They both work the same way, except th...

  • Page 188

    152 Chapter 4exercise solutionfunction ____________(___________, ____________, rating, showtimes) { this.title = ___________; this.genre = genre; this.________________ = rating; this.showtimes = ________________; this.getNextShowing = function() { var now = new Date().getTi...

  • Page 189

    you are here 4 153javascript functions and objectsvar banzaiMovie = new Movie("Buckaroo Banzai", "Cult Classic", 5, ["1:00pm", "5:00pm", "7:00pm", "11:00pm"...;

  • Page 190

    154 Chapter 4tour of common objectsmovietitle genre rating showtimes getNextShowingCongrats, you’ve made it through functions and objects! Now that you know all about them, and before we end the chapter, let’s take a few moments to check out JavaScript objects in the wild; that is, in their...

  • Page 191

    you are here 4 155javascript functions and objectsWhen you’re writing code for the browser, the window object is always going to be part of your life. The window object represents both the global environment for your JavaScript programs and the main window of your app, and as such, it contains...

  • Page 192

    156 Chapter 4how window.onload worksWe’ve been writing “alert”, not “window.alert”... how does the browser know we want the window alert method?Window is the global object.It may seem a little weird, but the window object acts as your global environment, so the names of any properties ...

  • Page 193

    you are here 4 157javascript functions and objectsAnother look at the document objectThe document object is another familar face; it’s the object we’ve been using to access the DOM. And, as you’ve just seen, it is actually a property of the window object. Of course we haven’t used it lik...

  • Page 194

    158 Chapter 4the element objectOne more object to think about: your element objectsWe shouldn’t forget when we’re working with methods like getElementById that the elements they return are also objects! Okay, you might not have realized this, but now that you know, you might be starting to t...

  • Page 195

    you are here 4 159javascript functions and objectsQ: Which of the two ways of creating a window.onload handler is better, using a function name or an anonymous function?A: One isn’t better than the other, they both do basically the same thing: set the value of window.onload to a function that ...

  • Page 196

    160 Chapter 4review of functions and objects ƒTo create a function, use the function keyword with parentheses to hold parameters, if there are any. ƒFunctions can be named, or be anonymous. ƒNaming rules for functions are the same as naming rules for variables. ƒThe body of a function goes b...

  • Page 197

    you are here 4 161javascript functions and objectsHTML5crossIt’s been a whirlwind chapter of functions, objects, properties and methods—so there’s lots to make stick. Sit back, relax, and work the rest of your brain a little. Here’s your Chapter 4 crossword puzzle.12345678910111213141516...

  • Page 198

    162 Chapter 4exercise solutionsUse your knowledge of functions and passing arguments to parameters to evaluate the code below. After you’ve traced through the code, write the value of each variable below. Here’s our solution.function dogsage(age) { return age * 7;}function rectanglearea(w...

  • Page 199

    you are here 4 163javascript functions and objectsHTML5cross SolutionL1O C2A LOR3W4I N D O WC5ESHD6O7C U M E N TA8TD9ANURROIU10V11A L U ERGF12U N C TI O NPT13ONUCIPHAMTU14N D E FI N E DM15E T H O DG16GRSNRLCTOA17N O N Y M O U SSBSP18A R A M E T E R SLAcross1. These variables are only available i...

  • Page 200

    actionURI(https://freepdf-books.com /):www.freepdf-books.com actionURI(https://freepdf-books.com /):https://freepdf-books.com

  • Page 201

    this is a new chapter 165Wherever you go, there you are. And sometimes knowing where you are makes all the difference (especially to a web app). In this chapter we’re going to show you how to create web pages that are location aware—sometimes you’ll be able to pinpoint your users down to t...

  • Page 202

    166 Chapter 5the geolocation apiQ: I heard Geolocation isn’t a real API?A: Geolocation is not considered a first-class member of the existing HTML5 standard, but that said, it is a standard of the W3C, widely supported and pretty much everyone includes Geolocation in the list of important HTML...

  • Page 203

    you are here 4 167making your html location awareThe Lat and Long of it...To know where you are, you need a coordinate system, and you need one on the Earth’s surface. Luckily we have such a thing, and it uses latitude and longitude together as a coordinate system. Latitude specifies a north/s...

  • Page 204

    168 Chapter 5determining locationHow the Geolocation API determines your locationYou don’t have to have the newest smartphone to be location aware. Even desktop browsers are joining the game. You might ask, how would a desktop browser determine its location if it doesn’t have GPS or any othe...

  • Page 205

    you are here 4 169making your html location awareMy phone is old school. No GPS on this baby. But through cell tower triangulation, my phone’s got a pretty good idea of where I am, and the browser can make use of this.WiFiWiFi positioning uses one or more WiFi access points to triangulate your...

  • Page 206

    170 Chapter 5method of determining locationIt’s cool we’ve got so many ways to know where we are. How am I going to know which method my device is using?You’re not.The short answer is “you’re not,” as the browser implementation is going to determine how location is determined. But th...

  • Page 207

    you are here 4 171making your html location awareThink about your existing HTML pages and applications (or ones that you want to create); how might you incorporate location information into them? Allow my users to share with others that are nearby.Let my users more easily find local resources or...

  • Page 208

    172 Chapter 5using the geolocation apiJust where are you anyway?<!doctype html><html><head> <meta charset="utf-8"> <title>Where am I?</title> <script src="myLoc.js"></script> <link rel="stylesheet" href="my...

  • Page 209

    you are here 4 173making your html location awarefunction displayLocation(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; var div = document.getElementById("location"); div.innerHTML = "You are at Latitude: " + latit...

  • Page 210

    174 Chapter 5reviewing geolocation codeWhat we just did...Now that we’ve got some geolocation code up and running (and, again, if you’re not seeing a location yet, hold on, we’re getting to some debugging techniques in just a sec), let’s walk through the code in a little more detail:if (...

  • Page 211

    you are here 4 175making your html location awarefunction displayLocation(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; var div = document.getElementById("location"); div.innerHTML = "You are at Latitude: " + latit...

  • Page 212

    176 Chapter 5how get current position worksHow it all fits togetherBrowsergeolocation APIBrowserBrowser calls getCurrentPositiongeolocation then asks the user for permission.If the user gives permission, then geolocation uses the best means it can to get the browser’s location (GPS, triangulat...

  • Page 213

    you are here 4 177making your html location awareWhen it comes to Geolocation, not every test drive is going to be successful, and even if your first test was successful, down the road something is going to go wrong. To help, we’ve created a little diagnostic test for you that you can add rig...

  • Page 214

    178 Chapter 5I did not give permission for my location to be used.My position wasn’t available.After a few seconds, I got a message indicating there was a request timeout.Nothing happened at all, no location and no error alert.Your Diagnostic Results HereSomething else ________________________...

  • Page 215

    you are here 4 179making your html location aware...<body> <div id="location"> Your location will go here. </div> <div id="distance"> Distance from WickedlySmart HQ will go here. </div></body></html>Revealing our secret locat...

  • Page 216

    180 Chapter 5ready bake code to compute distancefunction degreesToRadians(degrees) { var radians = (degrees * Math.PI)/180; return radians;}We’ll see more of this function in the Canvas chapter.Ever wanted to know how to compute the distance between two points on a sphere? You’ll find ...

  • Page 217

    you are here 4 181making your html location awareWe want to compute the distance from you to us, as the crow flies.Writing the code to find the distancevar ourCoords = { latitude: 47.624851, longitude: -122.52099};Now that we’ve got a function to compute the distance between two...

  • Page 218

    182 Chapter 5adding google mapsYou know, seeing my location as 34.20472, -90.57528 is great, but a map would really come in handy right now!<script src="http://maps.google.com/maps/api/js?sensor=true"></script>This is the location of the Google Maps JavaScript API.Make sure...

  • Page 219

    you are here 4 183making your html location awareNow that you’ve linked to the Google Map API, all the functionality of Google Maps is available to you through JavaScript. But, we need a place to put our Google Map, and to do that we need to define an element that is going to hold it.Here’s ...

  • Page 220

    184 Chapter 5page goal headervar map;function showMap(coords) { var googleLatandLong = new google.maps.LatLng(coords.latitude, coords.longitude); var mapOptions = { zoom: 10, center: googleLatandLong, mapTypeId: goo...

  • Page 221

    you are here 4 185making your html location awareOffRoad DiversionMake sure you’ve added all the new code on the previous page and also added the new map <div> to your HTML; then reload your page and, if the browser can determine your location, you’ll see a map.We’re showing the b...

  • Page 222

    186 Chapter 5page goal headerIt would be more useful if you could see exactly where you’re located on the map. If you’ve used Google Maps, then you’re probably familiar with the push pins used to mark the location of items you search for. For example, if you search for Space Needle in Seat...

  • Page 223

    you are here 4 187making your html location awarefunction addMarker(map, latlong, title, content) { . . . var infoWindowOptions = { content: content, position: latlong }; var infoWindow = new google.maps.InfoWindow(infoWindowOptions); google.maps.event.addListener(ma...

  • Page 224

    188 Chapter 5page goal headerOffRoad DiversionGet all the code for addMarker added, update showMap to call addMarker and reload the page. You’ll see a map with a marker with your location on it. Try clicking on the marker. You’ll get a pop-up window with your latitude and longitude. This ...

  • Page 225

    you are here 4 189making your html location awareHead First: Welcome Geolocation. I gotta say right up front, I’m a bit surprised to see you here.Geolocation: Why’s that?Head First: You’re not even “officially” part of the HTML5 spec and here you are, you’re the first API that’s be...

  • Page 226

    190 Chapter 5geolocation api detailsMeanwhile back at the Geolocation API...We’ve already travelled a fair distance with the Geolocation API: we’ve determined our location, computed distances to other locations, handled the error states of the API and even added a map using the Google Maps A...

  • Page 227

    you are here 4 191making your html location awareCan we talk about your accuracy?Finding your location isn’t an exact science. Depending on the method the browser uses, you may know only the state, city, or city block you’re on. Then again, with more advanced devices you might know your loc...

  • Page 228

    192 Chapter 5tracking movement“Wherever you go, there you are”The orgin of this phrase has been hotly debated. Some claim the first real mention of it was in the film Buckaroo Banzai, others draw its origin from Zen Buddhist text, still others cite various books, movies and popular songs. N...

  • Page 229

    you are here 4 193making your html location awareGetting the app startedWe’re going to use our previous code as a starting point; first we’re going to add a couple of buttons to the HTML so that we can start and stop the tracking of your location. Why do we need the buttons? Well, first of...

  • Page 230

    194 Chapter 5using watchpositionSo now we need to add button click handlers for the two buttons. We’ll add them to the getMyLocation function only if there is geolocation support. And, since we’re going to control all the geolocation tracking using the two buttons, we’ll remove the existi...

  • Page 231

    you are here 4 195making your html location awarefunction clearWatch() { if (watchId) { navigator.geolocation.clearWatch(watchId); watchId = null; }}...call the geolocation.clearWatch method, passing in the watchId. This stops the watching.Writing the clearWatch handlerNow let�...

  • Page 232

    196 Chapter 5testing user trackingTime to get moving!Make sure you’ve got all the new code typed in and reload your page, myLoc.html. Now, to truly test this page you’re going to need to “relocate” to have your position updated. So take a walk, jump on your bike, get in the car, or use w...

  • Page 233

    you are here 4 197making your html location awareQ: How can I control the rate at which the browser is providing updates of my location when using watchPosition?A: You can’t. The browser determines what the optimal update rate is and decides when you’ve changed positions.Q: Why does my locat...

  • Page 234

    198 Chapter 5overview of geolocation objectsYou’ve got some Options...So far we’ve stayed away from the third parameter of getCurrentPosition (and watchPosition): the positionOptions parameter. With this parameter we can control how geolocation computes its values. Let’s look at the three...

  • Page 235

    you are here 4 199making your html location awareThe world of timeouts and maximum age...Let’s review once again what the timeout and maximumAge options are:timeout: this option tells the browser how long it gets to determine the user’s location. Note that if the user is prompted to approve ...

  • Page 236

    200 Chapter 5exercise on using geolocation optionsI’ll use a cached position if the browser has one that’s less than 10 minutes old, otherwise, I want a fresh position.Below you’ll see a few options for the geolocation API. For each option, match it to its behavior.{maximumage:600000}{time...

  • Page 237

    you are here 4 201making your html location awareHow to specify optionsOne of the nice things about JavaScript is that if we want to specify a set of options in an object, we can just type in a literal object, right into the middle of our method call. Here’s how you do that: let’s say we wan...

  • Page 238

    202 Chapter 5Wouldn’t it be fun to see how fast your browser can find your location? We could make it as hard for your browser as we can: ƒ let’s ask it to enable high accuracy, ƒ let’s not allow it to use a cache (by setting maximumAge to 0) ƒ let’s time it by setting the time...

  • Page 239

    you are here 4 203making your html location awarevar options = { enableHighaccuracy: true, timeout:100, maximumage: 0 };window.onload = getMyLocation;function getMyLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( displayLocation, ...

  • Page 240

    204 Chapter 5adding a path to the mapLet’s finish this app!When you sit back and think about it, with just a little HTML and JavaScript you’ve created a web app that not only can determine your location, but it can also track and display it in near real time. Wow, HTML sure has grown up (an...

  • Page 241

    you are here 4 205making your html location awarefunction displayLocation(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; var div = document.getElementById("location"); div.innerHTML = "You are at Latitude: " + latit...

  • Page 242

    206 Chapter 5optimizing marker usagevar ___________________;function displayLocation(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; var div = document.getElementById("location"); div.innerHTML = "You are at Latitude: &qu...;

  • Page 243

    you are here 4 207making your html location aware ƒGeolocation is not “officially” part of the HTML5 specification, but it’s considered part of the “family” of HTML5 specs. ƒThere are a variety of ways to determine your location, depending on the device you have. ƒGPS is a more accu...

  • Page 244

    208 Chapter 5exercise solutionsHTML5crossYou’ve traveled quite far in this chapter with your first JavaScript API. Make it stick with this crossword.1234567891011Across4. Longitude is measured from _____________, England.7. Accuracy has implications for your app because it can affect _________...

  • Page 245

    you are here 4 209making your html location awarevar ________________________function displayLocation(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; var div = document.getElementById("location"); div.innerHTML = "You are...

  • Page 246

    210 Chapter 5exercise solutionsWrite what you think this does here.This code turns our app into a Hot/Cold game. It displays a “getting hotter” message if you’re moving closer to the WickedlySmart HQ, or “getting colder” if you’re moving farther away. If you’re within 0.1 km of the...

  • Page 247

    you are here 4 211making your html location awareI’ll use a cached position if the browser has one that’s less than 10 minutes old, otherwise, I want a fresh position.Below you’ll see a few options for the geolocation API. For each option, match it to its behavior.{maximumage:600000}{timeo...

  • Page 248

    212 Chapter 5exercise solutionsHTML5cross SolutionP1T2N3ARG4R E E N W I C HM5WTAAH6B7A T T E R YONXAOGIVE8R R O RUMEKLB9U C K A R O O B A N Z AIA10C C U R A C YMSITAW11I C K E D L Y S M A R TIGNYOEENAcross4. Longitude is measured from _____________, England. [GREENWICH] 7. Accuracy has implicati...

  • Page 249

    this is a new chapter 213talking to the web6Extroverted AppsYou’ve been sitting in your page for too long. It’s time to get out a little, to talk to web services, to gather data and to bring it all back so you can build better experiences mixing all that great data together. That's a big par...

  • Page 250

    214 Chapter 6the mighty gumball appThis just in: Mighty Gumball, Inc., an innovative company that builds and deploys real gumball machines, has contacted us for some help. If you’re not up on them, they’ve recently network-enabled their gumball machines to track sales in near real time.Now i...

  • Page 251

    you are here 4 215talking to the webEngineering NotesMighty Gumball, Inc.Where the Gumball Machine is Never Half EmptyBefore we get started, take a little time to think through how you might design an app that retrieves data from a web service and then keeps a web page updated based on the data....

  • Page 252

    216 Chapter 6overview of mighty gumballYou probably need a little background beyond Mighty Gumball’s short note. Here’s what we’ve got: first, they’ve got gumball machines all over the country sending sales reports to a Mighty Gumball server, which combines all those reports and makes t...

  • Page 253

    you are here 4 217talking to the webdocumentheadhtmltitlescriptbodyh1ulThe browser loads the Mighty Gumball web app, including the HTML markup, CSS and JavaScript.2The app makes a Web request to retrieve the aggregated sales from the Gumball server.3requestThe app receives data back from the Gum...

  • Page 254

    218 Chapter 6preparing the markupWhile we’re waiting on those specs from Mighty Gumball, let’s get some HTML going.You’re probably getting the idea we don’t need a lot of HTML markup to get a web app off the ground, and you’re right. All we need is a place to put our sales reports as t...

  • Page 255

    you are here 4 219talking to the webSo how do we make requests to web services?Let’s step back for a sec... you already know how a browser requests a page from a web server—it makes an HTTP request to the server, which returns the page along with other metadata that (typically) only the brow...

  • Page 256

    220 Chapter 6using xmlhttprequestHow to make a request from JavaScriptOkay, so we know we can retrieve data with HTTP, but how? We’re going to write a little code to create an actual HTTP request and then ask the browser to make the request on our behalf. After it’s made the request, the bro...

  • Page 257

    you are here 4 221talking to the webOkay here’s the important part, and the trick of how XMLHttpRequest works: when we finally ask our XMLHttpRequest object to retrieve data, it’s going to go off on its own and get the data. It might take a 90 milliseconds (quite a while in compute time), or...

  • Page 258

    222 Chapter 6how to access an http responseOne thing I didn’t notice is how we get the data from the HTTP call. I see the onload function, but no code to access the data? Did I miss something?We just hadn’t quite got there yet. The data from the HTTP GET retrieval can be found in the respons...

  • Page 259

    you are here 4 223talking to the webYour magnets go here!Code MagnetsA new web service at http://wickedlysmart.com/ifeelluckytoday returns either “unlucky” or “lucky” each time you hit it. The logic is based on a secret and ancient algorithm we can’t reveal, but it’s a great service ...

  • Page 260

    224 Chapter 6exercise solutionwindow.onload = function () { var url = "http://wickedlysmart.com/ifeelluckytoday"; var request = ______________________ ____________________________ { if (________________________) { displayLuck(_______________________); ...

  • Page 261

    you are here 4 225talking to the webHead First: Welcome XMLHttpRequest, we’re glad you could fit us into your busy schedule. Tell us about how you fit into building web apps.XMLHttpRequest: I started this whole trend for bringing outside data into your web page. Heard of Google Maps? GMail? Th...

  • Page 262

    226 Chapter 6introducing jsonYou might (or might not) remember that XML was going to save us all—a data format that was human readable and machine parseable, a data format that was going to support all the data needs of the world. And when XMLHttpRequest was first developed, XML was indeed the...

  • Page 263

    you are here 4 227talking to the webLet’s run through a quick example that converts an object into its JSON string format. We’ll start with an object you already understand, the Movie object from Chapter 4. Not everything can be converted into a JSON string—for instance, methods—but all ...

  • Page 264

    228 Chapter 6reviewing the mightygumball specificationshttp://gumball.wickedlysmart.com/Thanks for taking this on!!!We’ve got all the sales from the Gumball machines aggregated and being served from our central server at:We’ve chosen JSON as our data format and if you hit the above URL, you�...

  • Page 265

    you are here 4 229talking to the web If you're using Opera or IE 8 or older, we recommend you test with another browser. We'll talk about how to support Opera and older IE browsers later.window.onload = function() { var url = "http://localhost/sales.json"; var request =...

  • Page 266

    230 Chapter 6how to test locallyIt’s time for another test drive, but we have a little detour to take care of first. The Mighty Gumball engineers asked us to test locally before hitting their production server, which is a good idea. But to do that we need the data to live on a server so that ...

  • Page 267

    you are here 4 231talking to the webI’m a MacSetting up a web server on the Mac is easy. Go to > System Preferences, and then choose Sharing. In the panel on the left, make sure Web Sharing is checked:Once you’ve turned Web Sharing on (or if you already have it on), you’ll see som...

  • Page 268

    232 Chapter 6If you don’t want to set up your own server, you can always use a remote server, but you’ll need to host your HTML, JavaScript and CSS, as well as the JSON file, all on the same server (we’ll talk later about why this is crucial) in order to follow along with this example. Mos...

  • Page 269

    you are here 4 233talking to the webBack to the codeAt this point we’re expecting you’ve got your own server up and running—that could be a server running on your local machine (what we’re doing) or a server somewhere else you have access to. In either case you’re going to place your H...

  • Page 270

    234 Chapter 6testing mighty gumball version oneRemember we’re sending an HTTP request to get the data in sales.json, which we’re just dumping into the <div> for now. Looks like it worked! If you’re having trouble, check each file independently through your browser and make sure it is...

  • Page 271

    you are here 4 235talking to the webImpressing the client...We’ve done a lot of heavy lifting to get this app working, and that’s great, but Mighty Gumball is going to be a lot more impressed if it looks good too. Here’s what we’re going for...What we haveAt the moment we’re just dumpi...

  • Page 272

    236 Chapter 6adding json supportfunction updateSales(responseText) { var salesDiv = document.getElementById("sales"); var sales = JSON.parse(responseText); for (var i = 0; i < sales.length; i++) { var sale = sales[i]; var div = document.createElement("div...

  • Page 273

    you are here 4 237talking to the webThe Home Stretch...You already know what this one is going to look like, but go ahead and make these changes. Take one more careful look at the code on the previous page and make sure you’ve got it all down. Then go ahead, reload that page.See, we told you...

  • Page 274

    238 Chapter 6a problem with mighty gumballA Live Test Drive...Make sure your URL change is saved in your mightygumball.js file on your server, if you want to keep retrieving your HTML from there, or to your local hard drive if you are using localhost. From there you know what to do: point your b...

  • Page 275

    you are here 4 239talking to the webWe’re not seeing any data in our page. It was all working fine until we moved to the live server...Will we find the problem?Will we fix it?Stay tuned... we’ll answer these questions, and more...And in the meantime, see if you can come up with ideas for wha...

  • Page 276

    240 Chapter 6interviewing xmlhttprequestHead First: Welcome back to the second part of the interview, XMLHttpRequest. I wanted to ask you about browser support—are you available in only the newer browsers only?XMLHttpRequest: The guys don’t call me “old man” for nothing; I’ve been supp...

  • Page 277

    you are here 4 241talking to the webfunction init() { var url = "http://localhost/gumball/sales.json"; var request = new xMLHttpRequest(); request.onreadystatechange = function() { if (request.readyState == 4 && request.status == 200) { updateSales(re...

  • Page 278

    242 Chapter 6reviewing what went wrongRemember, we left you with a cliffhanger? A bug.We had all the code working just fine using our local server, but as soon as we moved to the live server on the Web, it failed!What we expected:What we got:Ajay, the Quality Assurance Guy, got pretty upset.Here...

  • Page 279

    you are here 4 243talking to the webJim: Do you have the correct URL?Frank: Yep, and in fact, I typed it into the browser to make sure I see the sales data we’re expecting, and it worked fine. I don’t get it...Joe: I peeked at the JavaScript console in Chrome and I see something about access...

  • Page 280

    244 Chapter 6browser security overviewFirst the user (through the browser) makes a request for an HTML page (and, of course, any associated JavaScript and CSS):The page needs some data from GoodDomain.com so it makes a XMLHttpRequest for the data:21Server happily serves you your page.Your browse...

  • Page 281

    you are here 4 245talking to the webUnacceptable Behavior for JavaScript code:Just like before, the browser makes a request for a page on GoodDomain.com. This may include JavaScript and CSS files that are also hosted at GoodDomain.com.But now we have code that wants data from another source, tha...

  • Page 282

    246 Chapter 6reviewing our optionsNice job, all this code and this won’t even work? Can’t we just copy our files to the Mighty Gumball servers?Usually the answer is yes. Say you were a developer working on code for Mighty Gumball, then you’d typically have access to their servers (or to p...

  • Page 283

    you are here 4 247talking to the webSo, what are our options?We gotta be honest with you, we knew all along that the XMLHttpRequest cross-origin request would fail. But, as we just said, when you’re building apps you’ve often got access to the server and so this isn’t an issue (and if you�...

  • Page 284

    248 Chapter 6introducing jsonpJoe: Totally! But, what is it?Jim: Sounds like it is another way to get data from web services into our apps.Frank: I’m useless here, I’m just the creative guy.Jim: Frank, I don’t think this is that bad. I quickly google’d JSONP and basically it is a way of ...

  • Page 285

    you are here 4 249talking to the webHTML5 Guru: ...and this is one of those times. Grasshopper, look at the this code: What does it do?Web Developer: When you evaluate it, assuming it is running in a browser, it will display an alert saying “woof”.Guru: Ah, yes. Create your own simple HTML...

  • Page 286

    250 Chapter 6the guru teaches jsonpWeb Developer: It’s similar to dog.js, but it calls a function animalSays. It also has two arguments not one: the animal type, and the animal sound.Guru: Write the function animalSays and add it in a <script> element in the head of your HTML file, above...

  • Page 287

    you are here 4 251talking to the webWeb Developer: How’s this?Guru: Very good. Change your reference to http://wickedlysmart.com/hfhtml5/chapter6/dog3.js and try it. Try http://wickedlysmart.com/hfhtml5/chapter6/cat3.js too.Web Developer: Yes, both work as you would expect with my new function...

  • Page 288

    252 Chapter 6jsonp overviewMeet JSONPYou’ve probably figured out that JSONP is a way to retrieve JSON objects by using the <script> tag. It’s also a way of retrieving data (again, in the form of JSON objects) that avoids the same-origin security issues we saw with XMLHttpRequest. Let�...

  • Page 289

    you are here 4 253talking to the webBut what is the “P” in JSONP for?OK, the first thing you need to know about JSONP is it has a dumb and non-obvious name: “JSON with Padding.” If we had to name it, we’d call it something like “JSON with a Callback” or “get me some JSON and exe...

  • Page 290

    254 Chapter 6dealing with callbackshttp://gumball.wickedlysmart.com/?callback=updateSalesI see how to use the <script> tag to make the browser go retrieve JavaScript, and how the server can put its data in that JavaScript. What about the function name though? How does the web service know ...

  • Page 291

    you are here 4 255talking to the webGuys, we’ve got this. It took us a while to wrap our heads around using a <script> element to hit a web service, but now it almost seems easier than using XMLHttpRequest.Jim: Well, almost.Joe: I think this actually allows us to delete some code.Frank: ...

  • Page 292

    256 Chapter 6reimplementation planLet’s update the Mighty Gumball web appIt’s time to update your Mighty Gumball code with JSONP. Other than removing the existing code that deals with the XMLHttpRequest call, all the changes are minor. Let’s make those changes now:Remove our XMLHttpReques...

  • Page 293

    you are here 4 257talking to the web<!doctype html><html lang="en"><head> <title>Mighty Gumball</title> <meta charset="utf-8"> <script src="mightygumball.js"></script> <link rel="stylesheet" href="...;

  • Page 294

    258 Chapter 6testing jsonpTest drive your new JSONP-charged codeIf you’ve made all your changes, it’s time for a test drive. Reload mightygumball.html into your browser. You’re now loading Mighty Gumball sales data using your web app and JSONP. The page should look the same as when you wer...

  • Page 295

    you are here 4 259talking to the webIt’s not any more or less secure than using <script> to load JavaScript.It’s true: if you make a JSONP request to a malicious web service, the response could include JavaScript code you’re not expecting and the browser will execute it. But it’s n...

  • Page 296

    260 Chapter 6a chat with xmlhttprequest and jsonpTonight, we have two popular methods of retrieving data from your browser.Tonight’s talk: XMLHttpRequest and JSONPXMLHttpRequest:No offense meant, but aren’t you kind of a hack? I mean your purpose is to retrieve code, and people are using you...

  • Page 297

    you are here 4 261talking to the webXMLHttpRequest: I had nothing to do with the name Ajax, so don’t ask me! By the way, you never said how you are secure? All I can say is if you don’t need to go get someone else’s data, like Twitter or Google, and you’re writing your own web service...

  • Page 298

    262 Chapter 6exercising your brain with jsonpYou came up a little short. I thought I was going to see a constantly updated stream of sales from my gumball machines. Sure, I could hit refresh on my browser, but then I see only the newest reports, and only when I manually refresh. That’s not w...

  • Page 299

    you are here 4 263talking to the webJim: Yeah, he wants the data to be continually updated in the display.Judy: That does make sense. I mean one big advantage of a web app is you don’t have to refresh it like a web page.Joe: Fair enough, and obviously we know how to replace old sales data with...

  • Page 300

    264 Chapter 6making jsonp dynamicThen we need to implement our JSONP code in the handler, so that each time it is called it makes a request to get the latest Mighty Gumball sales reports. Here’s what we need to do:We're going to remove the JSONP <script> element from the Mighty Gumball ...

  • Page 301

    you are here 4 265talking to the webOkay, we’re progressing from retrieving the sales reports once, to retrieving them every so often, say every three seconds. That might be too fast or slow depending on the application, but for Mighty Gumball we’re going to start with three seconds.Now, to ...

  • Page 302

    266 Chapter 6testing an interval timerA time-driven test driveThis should be fun. Make sure you’ve typed in the handleRefresh function and also made the changes to the onload handler. Save everything and load it into your browser. You’ll see a stream of alerts, and you’ll have to close you...

  • Page 303

    you are here 4 267talking to the webStep 3: Reimplementing JSONPHere, we’re setting up the JSONP URL and assigning it to the variable url.... and set the src attribute of the element to our JSONP URL.function handleRefresh() { var url = "http://gumball.wickedlysmart.com?callback=update...

  • Page 304

    268 Chapter 6jsonp dom insertionHow do we insert the script into the DOM?We’re almost there, we just need to insert our newly created script element. Once we do that the browser will see it and do its thing, causing the JSONP request to be made. Now, to insert the script requires a little bit ...

  • Page 305

    you are here 4 269talking to the webNow let’s write the code to insert the script into the DOMNow that we know the steps, let’s check out the code. We’ll do this in two steps too: first we’ll show the code to add a new script, then the code to replace a script:function handleRefresh() { ...

  • Page 306

    270 Chapter 6closeup of more dom methodsThe replaceChild method tells the <head> element to replace one of its children, oldScriptElement, with a new child, newScriptElement.Our new <script> elementThe <script> that’s already in the page.head.replaceChild(newScriptElement, ol...

  • Page 307

    you are here 4 271talking to the webQ: Why can’t I just replace the data in the src attribute instead of replacing the whole <script> element?A: If you replace just the src attribute with the new URL, the browser doesn’t see it as a new script, and so it doesn’t make the request to r...

  • Page 308

    272 Chapter 6handling the browser cacheWe almost forgot: watch out for the dreaded browser cacheWe’re almost ready to go here, but there’s a small detail we need to take care of, and it’s one of those “if you’ve never done it before, how would you know you need to address it” kind of...

  • Page 309

    you are here 4 273talking to the web[{"name":"LOS aNGELES","time":1309208126092,"sales":2}, {"name":"PaSaDENa","time":1309208128219,"sales":8}, {"name":"DavIS CREEk","time":1309214414505...

  • Page 310

    274 Chapter 6using a web service parameterYou got it.And to keep track of the last sales report received we’re going to need to make some additions to the updateSales function, where all the processing of the sales data happens. First, though, we should declare a variable to hold the time of t...

  • Page 311

    you are here 4 275talking to the webfunction handleRefresh() { var url = "http://gumball.wickedlysmart.com" + "?callback=updateSales" + "&lastreporttime=" + lastReportTime + "&random=" + (new Date())....

  • Page 312

    276 Chapter 6You’ve outdone yourselves! This works great and now I can totally keep up with sales at my desk or when I’m mobile. I’m starting to really think there is something to these web apps. Just think what we’re going to be able to do with gumball machines, JSON, and all those HTML...

  • Page 313

    you are here 4 277talking to the web ƒXMLHttpRequest does not allow you to request data from a different server than the one from which your HTML and JavaScript are being served. This is a browser security policy designed to prevent malicious JavaScript from getting access to your web pages and...

  • Page 314

    278 Chapter 6giving your brain some exerciseHTML5crossWow, you got your apps talking to the Web in this chapter! Time for some left‑brain activity to help it all sink in.123456789101112 13141516Across2. The pattern of using XMLHttpRequest to get data from servers is sometimes called ______.5. ...

  • Page 315

    you are here 4 279talking to the webHelp us build tweetshirt.comWhile we’ve got you thinking about JSONP, we’d love to have your help in the Canvas chapter.We’re working with Twitter’s JSONP API and building out a service that allows you to put any tweet on a t-shirt.TweetShirt.com found...

  • Page 316

    280 Chapter 6exercise solutionsHTML5cross SolutionC1AA2J3A X4LAM5G 2 2 0 0LT6VLBWC7AP8A D DI N GLSC9CTICD10A T AKTJ11FRLEUFIIE12M13B A R R A S S E DHPFA14AYA15C TIV E X O B J E C TNRAGNYEIRP16A D DI N GAcross2. The pattern of using XMLHttpRequest to get data from servers is sometimes called ____...

  • Page 317

    this is a new chapter 281HTML’s been liberated from being just a “markup” language. With HTML5’s new canvas element, you’ve got the power to create, manipulate and destroy pixels, right in your own hands. In this chapter we'll use the canvas element to bring out your inner artist—no ...

  • Page 318

    282 Chapter 7the new start-up tweetshirtOur new start-up: TweetShirtOur motto is “if it’s worth tweeting on Twitter, it’s worth wearing on a t-shirt.” After all, half the battle of calling yourself a journalist is being willing to put your words in print, so what better place than printi...

  • Page 319

    you are here 4 283bringing out your inner artistTweetShirt.com, Strictly ConfidentialChecking out the “comps”After exhaustive iterative design and extensive focus group testing we’ve got a comp (otherwise known as an initial visual design) ready for you to review, let’s take a look:Here�...

  • Page 320

    284 Chapter 7reviewing requirementsTake another look at the requirements on the previous page. How do you think you can accomplish this using HTML5? Remember, one requirement is making sure your site works across as many device formats and sizes as possible?Check all the possibilities below (and...

  • Page 321

    you are here 4 285bringing out your inner artistJoe: I thought this was going to be simple until I saw those circles in the background.Frank: What do you mean, that’s just an image...Judy: No no, the founder wants those circles to be random; so the circles on my shirt will be different from yo...

  • Page 322

    286 Chapter 7adding a canvas to your pageHow to get a canvas into your web pageFrank was right, in some ways a canvas is like an <img> element.You add a canvas like this:<canvas id="lookwhatIdrew" width="600" height="200"></canvas>And the browser a...

  • Page 323

    you are here 4 287bringing out your inner artist<!doctype html><html lang="en"><head> <title>Look What I Drew</title> <meta charset="utf-8"></head><body><canvas id="lookwhatIdrew" width="600" height=...

  • Page 324

    288 Chapter 7adding css for your canvas<!doctype html><html lang="en"><head> <title>Look What I Drew</title> <meta charset="utf-8"> <style> canvas { border: 1px solid black; } </style></head>&l...;

  • Page 325

    you are here 4 289bringing out your inner artistYou might have noticed that the canvas element didn’t have any content inside it. If you were to place text between the tags, what do you think the browser would do when the page is loaded??<canvas></canvas>Q: Can I only have one canv...

  • Page 326

    290 Chapter 7drawing on a canvas<!doctype html><html lang="en"><head> <title>Look What I Drew</title> <meta charset="utf-8" /> <style> canvas { border: 1px solid black; } </style> <script> wind...

  • Page 327

    you are here 4 291bringing out your inner artistHere's our 100 x 100 rectangle, positioned at 10, 10 in the canvas. And our canvas, which is 600 wide, 200 high and has a 1 pixel black border around it.A closer look at the codeThat was a great little test run, but let’s dive in a little deeper:...

  • Page 328

    292 Chapter 7reviewing how canvas code worksvar context = canvas.getContext("2d");context.fillRect(10, 10, 100, 100);This is a bit of protocol we have to follow before we can start drawing on the canvas.Try this out and you should see a black rectangle appear. Try changing the values f...

  • Page 329

    you are here 4 293bringing out your inner artistQ: How does the canvas know to make the rectangle black?A: Black is the default fill color for a canvas.Of course, you can change this using the fillStyle property, as we’ll show you shortly.Q: What if I wanted a rectangle outline, not a filled r...

  • Page 330

    294 Chapter 7canvas and internet explorerIE supports canvas only in versions 9 and later, so you should code your page to let your users know.Here’s the deal: if you really really need to support canvas functionality in Internet Explorer (again, pre-version 9), then you can check out the Explo...

  • Page 331

    you are here 4 295bringing out your inner artistSo, the truth is, out there somewhere, in another place and time, a user is going to visit your site and not have support for the canvas element. Would you like to send them a kind message saying that they really should upgrade? Here’s how:Failin...

  • Page 332

    296 Chapter 7reviewing the implementation planFrank: Sure, but also we need the user interface for the user to specify all this. I mean we’ve got the mock-up, but we need to implement it.Judy: You’re right Frank. Not much point in going further without the interface.Joe: Isn’t that just HT...

  • Page 333

    you are here 4 297bringing out your inner artistTweetShirt: the Big PictureBefore we jump into a big implementation job, let’s step back and look at the big picture. We’re going to build this web app out of a canvas element along with some form elements that act as the user interface, and be...

  • Page 334

    298 Chapter 7BE the BrowserBelow, you’ll find the form for the t-shirt interface. Your job is to play like you’re the browser and to render the interface. After you’re done, compare your interface to the one on the previous page to see if you did it correctly.<form><p> <l...

  • Page 335

    you are here 4 299bringing out your inner artistRender your interface here. Draw the web page as it will look with the form elements on the left.BE the Browser, againNow that you have an interface, execute these JavaScript statements and write in the value for each interface element. Check your ...

  • Page 336

    300 Chapter 7creating the htmlFirst, let’s get the HTML in placeEnough talk! Let’s build this thing. Before we do anything else, we just need a simple HTML page. Update your index.html file so it looks like this:<!doctype html><html lang="en"><head> <title&...

  • Page 337

    you are here 4 301bringing out your inner artist<form><p> <label for="backgroundColor">Select background color:</label> <select id="backgroundColor"> <option value="white" selected="selected">White</optio...

  • Page 338

    302 Chapter 7adding the javascriptTime to get computational, with JavaScriptMarkup is great, but it’s the JavaScript that brings the TweetShirt web application together. We’re going to put some code into tweetshirt.js. Right now, we want to take the baby step of just putting random squares o...

  • Page 339

    you are here 4 303bringing out your inner artistset the fillStyle to "lightblue"function drawSquare ( , ){}calculate a random width for the squarecalculate a random x position for the square inside the canvascalculate a random y position for the square inside the canva...

  • Page 340

    304 Chapter 7implementing the squaresfunction drawSquare(canvas, context) { var w = Math.floor(Math.random() * 40); var x = Math.floor(Math.random() * canvas.width); var y = Math.floor(Math.random() * canvas.height); context.fillStyle = "lightblue"; context.fillRect(x, y...

  • Page 341

    you are here 4 305bringing out your inner artistTime for a test drive!Okay, after all that typing, let’s give all this code a test run. Go ahead and open your TweetShirt index.html file in your browser. Press preview and you should see random blue squares. Here’s what we see:Uh, wait a sec,...

  • Page 342

    306 Chapter 7fixing the squares codeWhy are we seeing the old squares and the new squares when we preview?This is actually kind of a cool effect... but it’s not what we wanted. We want the new squares to replace the old squares each time we press preview (just like we’ll also want the new tw...

  • Page 343

    you are here 4 307bringing out your inner artistCount the squares in a few different previews. Do you ever see less than 20 squares? You might.Why would this happen? What could you do to fix this problem? (After all, you don’t want customers cheated out of their 20 squares, do you?)Another qui...

  • Page 344

    308 Chapter 7reviewing fill styleQ: I was expecting we’d set the background color of the squares and the canvas by passing in a color value to fillRect. I don’t really get how fillStyle works. How does it affect what fillRect does?A: Great question. This is a little different from how you mi...

  • Page 345

    you are here 4 309bringing out your inner artistJim: I know, and I’m impressed with how little code this took. Just think if we did this the old, server-side way, we’d still be getting our server up.Frank: And it seems like we’re in a good position to knock out the circles in the design t...

  • Page 346

    310 Chapter 7introducing paths and arcsAnd, a couple of hours later...Frank: I don’t know what’s going on, I’ve double checked everything, but, no matter what I do, when I call fillCircle, I get nothing on the canvas.Judy: Well, show me your fillCircle method.Frank: What do you mean by my ...

  • Page 347

    you are here 4 311bringing out your inner artistBefore digging into circles, we need to talk about paths and arcs. Let’s start with paths, and draw some triangles. If we want to draw a triangle on the canvas, there’s no fillTriangle method, but we can create a triangle anyway by first creati...

  • Page 348

    312 Chapter 7how to draw with pathsSo you have a path! Now what?You use the path to draw lines and fill in your shape with color, of course! Go ahead and create a simple HTML5 page with a canvas element and type in all the code so far. Give it a test run, too.Trace another line from the previous...

  • Page 349

    you are here 4 313bringing out your inner artistDo you happen to remember from geometry class that the circumference of a circle = 2 R? Just put that in the back of your mind for a sec...Just to keep us on track here, I thought we were trying to draw circles? What does all this path stuff have t...

  • Page 350

    314 Chapter 7looking at the arc methodBreaking down the arc methodcontext.arc(x, y, radius, startangle, endangle, direction)x,y The x and y parameters determine where the center of the circle will be located in your canvas.radius This parameter is used to specify 1/2 the width of the circl...

  • Page 351

    you are here 4 315bringing out your inner artistThe start angle is the angle between the x axis and the starting point of the arc.context.arc(x, y, radius, startangle, endangle, direction)startangle, endangle The start angle and end angle of the arc determine where your arc path starts ...

  • Page 352

    316 Chapter 7getting experience with arcWhat we need right now is a good example. Let’s say that you want to trace an arc over a circle that is centered at x=100, and y=100 and you want the circle to be 150 pixels wide (or, a radius of 75). And, the path you want to trace is just 1/4 of the ci...

  • Page 353

    you are here 4 317bringing out your inner artistWe all talk about circle angles every day: “nice 360 dude,” or “I was heading down that path and I did a complete 180,” or, ...well, you get the picture. The only problem is, we think in degrees, but the canvas context thinks in radians. No...

  • Page 354

    318 Chapter 7adding the circlesBack to writing the TweetShirt circle codefunction previewHandler() { var canvas = document.getElementById("tshirtCanvas"); var context = canvas.getContext("2d"); fillBackgroundColor(canvas, context); var selectObj = document.getElem...

  • Page 355

    you are here 4 319bringing out your inner artistfunction drawCircle(canvas, context) { var radius = Math.floor(Math.random() * 40); var x = Math.floor(Math.random() * canvas.width); var y = Math.floor(Math.random() * canvas.height); context.beginPath(); context.arc(x, y, radius, 0...

  • Page 356

    320 Chapter 7Whew! That was a fun set of pages we just went through. We don’t know about you, but we’re ready for some cookies. How about taking a short cookie break? But, don’t think we aren’t going to give you something fun to do while you’re having them (check on the exercise to the...

  • Page 357

    you are here 4 321bringing out your inner artistfunction drawSmileyFace() { var canvas = document.getElementById("smiley"); var context = canvas.getContext("2d"); context.beginPath(); context.arc(300, 300, 200, 0, degreesToRadians(360), true); context.fillStyle...

  • Page 358

    322 Chapter 7adding the jsonp for twitterYou’re back, you’re rested, refreshed, and we’re on the home stretch to getting this start-up off the ground. When you look at all the work we’ve done, all we really have left is to display the tweets and the other text in the canvas preview.Now, ...

  • Page 359

    you are here 4 323bringing out your inner artistfunction updateTweets(tweets) { var tweetsSelection = document.getElementById("tweets"); for (var i = 0; i < tweets.length; i++) { tweet = tweets[i]; var option = document.createElement("option"); o...

  • Page 360

    324 Chapter 7testing tweetshirt with twitterTest driving TweetsLet’s do a quick test drive. Make sure you’ve got all the code added to tweetshirt.js and index.html. Also make sure you’re using a Twitter username that has recent tweets in your script src URL (so you’ll be sure you see som...

  • Page 361

    you are here 4 325bringing out your inner artistFrank: Are you kidding me? I guess I’ll be working all weekend now.Jim: Gotcha! No seriously, there is a fillText method that takes the text to draw on the canvas along with the x, y position of where to draw it.Joe: That sounds pretty straightfo...

  • Page 362

    326 Chapter 7structure and presentation discussionThat’s a really good point.Now let’s work through why it’s set up this way. Remember that canvas is designed to give you a way to present graphics within the browser. Everything in the canvas is considered presentation, not content. So whil...

  • Page 363

    you are here 4 327bringing out your inner artistfunction drawText(canvas, context) { var selectObj = document.getElementById("__________________"); var index = selectObj.selectedIndex; var fgColor = selectObj[index].value; context._____________ = fgColor; context._______...

  • Page 364

    328 Chapter 7closer look at text in the canvasCanvas Text Up CloseNow that you’ve had a chance to draw your first text in the canvas, it’s time to take a closer look at the text methods and properties available in the canvas API. As you found out in the exercise this is a fairly low-level AP...

  • Page 365

    you are here 4 329bringing out your inner artistAlphabetAlphabetAlphabetAlphabetcontext.beginPath();context.moveTo(100, 100);context.lineTo(250, 100);context.stroke();context.textBaseline = "middle";context.fillText("alphabet", 100, 100);baselineThe textBaseline property sets...

  • Page 366

    330 Chapter 7drawing textGiving drawText a spinNow that you’ve got more of the API in your head, go ahead and get the code you created in the Magnet Code exercise typed in— here it is with the magnets nicely translated to code:Take a shot at completing the drawText function. You need to get...

  • Page 367

    you are here 4 331bringing out your inner artistfunction drawText(canvas, context) { var selectObj = document.getElementById("foregroundColor"); var index = selectObj.selectedIndex; var fgColor = selectObj[index].value; context.fillStyle = fgColor; context.font = "b...

  • Page 368

    332 Chapter 7launching tweetshirtYes! It works. We’re ready to launch!!Guys, I hate to burst your bubble, but you’re not done yet. You’re supposed to put an image of the Twitter bird on the t-shirt too!There’s the tweet on the t-shirt preview. Nice!Remember the TweetShirt founder?A quick...

  • Page 369

    you are here 4 333bringing out your inner artistThe first thing we need is an image. We’ve put an image named twitterBird.png in the TweetShirt folder. To get that into the canvas we first need a JavaScript image object. Here’s how we get one:1var twitterBird = new Image(); twitterBird.src ...

  • Page 370

    334 Chapter 7adding the imageYet another test driveDouble check your code and get in another test drive! Wow, this is really looking polished now. Give it a few tries; try it with circles or squares. You’ll notice that we used a png with a transparent background so that the circles and squares...

  • Page 371

    you are here 4 335bringing out your inner artistQ: We haven’t seen the Image object before. You used it when you added an image to the canvas. What is this? Why didn’t we create it with document.createElement(“img”)?A: Good catch. Both methods you mention create image objects. The JavaSc...

  • Page 372

    336 Chapter 7canvas metadataNo, that requires a little extra work.The canvas is really meant to be a simple drawing surface. When you draw a shape, the canvas just sees it as pixels. The canvas isn’t aware of the specifics of what you’re drawing, and it doesn’t keep track of any shapes. It...

  • Page 373

    you are here 4 337bringing out your inner artistCongrats team, you did it! And it even works on my iPad, so this is perfect for customers on the go. I’m thrilled. We’re throwing a TweetShirt launch party, so come join us. The TweetShirt founder also wanted to pass along that she’s happy to...

  • Page 374

    338 Chapter 7review of canvas ƒCanvas is an element you place in your page to create a drawing space. ƒThe canvas has no default style or content until you provide it (so you won’t see it on the page until you draw something in it or add a border with CSS). ƒYou can have more than one canva...

  • Page 375

    you are here 4 339bringing out your inner artistTHE WEBVILLEINQUiRERWe have the scoop, <canvas> and <video> are an item after all!Webville—You’ll hear it here firstAfter an exclusive interview we can report that <canvas> and <video> have been doing more than just shar...

  • Page 376

    340 Chapter 7some fun for your brainHTML5crossWe’re looking forward to checking out the <canvas> and <video> scoop in the next chapter. In the meantime, cement your new canvas knowledge with a quick crossword and perhaps a cup of tea.12345678910111213141516Across4. Everything on th...

  • Page 377

    you are here 4 341bringing out your inner artistBE the Browser SolutionNow that you have an interface, execute these JavaScript statements and write in the value for each interface element.var selectObj = document.getElementById("backgroundColor");var index = selectObj.selectedIndex;va...

  • Page 378

    342 Chapter 7exercise solutionsPseudo-code Magnets SolutionUse your pseudo-magical coding powers to arrange the pseudo code below. We need to write the pseudo-code for the drawSquare function. This function takes a canvas and context and draws one randomly sized square on the canvas. Here’s ou...

  • Page 379

    you are here 4 343bringing out your inner artistradius = 75ºstart angle = 270ºend angle = 0ºstart hereand draw counterclockwisearc pathcontext.arc(100, 100, 75, degreesToRadians(270), 0, true);BE the Browser SolutionInterpret the call to the arc method and sketch out all the values on the cir...

  • Page 380

    344 Chapter 7exercise solutionsfunction drawSmileyFace() { var canvas = document.getElementById("smiley"); var context = canvas.getContext("2d"); context.beginPath(); context.arc(300, 300, 200, 0, degreesToRadians(360), true); context.fillStyle = "#ffffcc&...

  • Page 381

    you are here 4 345bringing out your inner artistLeftover magnetsfunction drawText(canvas, context) { var selectObj = document.getElementById("__________________"); var index = selectObj.selectedIndex; var fgColor = selectObj[index].value; context.___________ = fgColor; c...

  • Page 382

    346 Chapter 7exercise solutionsSee if you can piece together the drawBird function from all the pieces Judy gave us. The drawBird function takes a canvas and context, and draws the bird onto the canvas. You can assume that with this function we’re placing “twitterBird.png” at the locatio...

  • Page 383

    you are here 4 347bringing out your inner artistTweetShirt Easter eggfunction makeImage() { var canvas = document.getElementById("tshirtCanvas"); canvas.onclick = function () { window.location = canvas.toDataURL("image/png"); };}window.onload = function() { ...

  • Page 384

    actionURI(https://freepdf-books.com /):www.freepdf-books.com actionURI(https://freepdf-books.com /):https://freepdf-books.com

  • Page 385

    this is a new chapter 349not your father’s tv8Video...with special guest star “Canvas”We don’t need no plug-in. After all, video is now a first-class member of the HTML family—just throw a <video> element in your page and you’ve got instant video, even across most devices. But...

  • Page 386

    350 Chapter 8announcing webville televisionWebville TV—all the content you’ve been waiting for, like Destination Earth, The Attack of the 50’ Woman, The Thing, The Blob, and it wouldn’t be beyond us to throw in a few ’50s educational films. What else would you expect in Webville? But t...

  • Page 387

    you are here 4 351not your father’s tvThe HTML, let’s get it done...<!doctype html><html lang="en"><head> <title>Webville Tv</title> <meta charset="utf-8"> <link rel="stylesheet" href="webvilletv.css"></h...

  • Page 388

    352 Chapter 8video formats can cause issuesYes, it’s probably the video format.While the browser makers have agreed on what the <video> element and API look like in HTML5, not everyone can agree on the actual format of the video files themselves. For instance if you are on Safari, H.264 ...

  • Page 389

    you are here 4 353not your father’s tvAt this point you’ve got a video up and playing on your page, but before we move on, let’s step back and look at that video element we used in our markup:How does the video element work?<video controls autoplay src="video/preroll...

  • Page 390

    354 Chapter 8overview of video attributesClosely inspecting the video attributes...The src attribute is just like the <img> element’s src—it is a URL that tells the video element where to find the source file. In this case, the source is video/preroll.mp4. (If you downloaded the code f...

  • Page 391

    you are here 4 355not your father’s tvThe controls look different on every browser; at least with solutions like Flash I had consistent looking controls.Yes, the controls in each browser are different with HTML video.The look and feel of your controls is dictated by those who implement the bro...

  • Page 392

    356 Chapter 8video format overviewWe wish everything was as neat and tidy as the video element and its attributes, but as it turns out, video formats are a bit of a mess on the Web. What’s a video format? Think about it this way: a video file contains two parts, a video part and an audio part,...

  • Page 393

    you are here 4 357not your father’s tvVP8, the contender, backed by Google, supported by others and coming on strong...MP4 container with H.264 Video and AAC AudioH.264 is licensed by the MPEG-LA group.There is more than one kind of H.264; each is known as a “profile.” MP4/H.264 is support...

  • Page 394

    358 Chapter 8managing video formatsHow to juggle all those formats...So we know it’s a messy world with respect to video format, but what to do? Depending on your audience you may decide to provide just one format of your video, or several. In either case, you can use one <source> elemen...

  • Page 395

    you are here 4 359not your father’s tvTelling the browser the location of your source files gives it a selection of different versions to choose from, however the browser has to do some detective work before it can truly determine if a file is playable. You can help your browser even more by g...

  • Page 396

    360 Chapter 8questions about video encoding and playbackQ: Is there any hope of getting to one container format or codec type in the next few years? Isn’t this why we have standards?A: There probably won’t be one encoding to rule them all anytime soon—as we said earlier, this topic interse...

  • Page 397

    you are here 4 361not your father’s tvYOUR NExT MISSION: vIDEO RECONNaISSaNCEGO OUT aND DETERMINE *THIS TExT WILL BE CUT* THE CURRENT LEvEL OF SUPPORT FOR vIDEO IN EaCH BROWSER BELOW (HINT, HERE aRE a FEW SITES THaT kEEP UP WITH SUCH THINGS: HTTP://EN.WIkIPEDIa.ORG/WIkI/HTML5_vIDEO, *REDaCT a...

  • Page 398

    362 Chapter 8supporting flash videoI think Flash video is still important and I want to make sure I have a fallback if my users’ browsers don’t support HTML5 video.No problem.There are techniques for falling back to another video player if your preferred one (whether that be HTML5 or Flash o...

  • Page 399

    you are here 4 363not your father’s tvI was told there would be APIs?playpauseprogresserrortimeupdateendedabortwaitingloadeddataloadedmetadatavolumechangeAs you can see, you can do a lot using markup and the <video> element. But the <video> element also exposes a rich API that you ...

  • Page 400

    364 Chapter 8how a playlist worksA little content “programming” on Webville TVSo far we’ve got one single video up and running on Webville TV. What we’d really like is a programming schedule that serves up a playlist of videos. Let’s say we want to do this on Webville TV:123Show a litt...

  • Page 401

    you are here 4 365not your father’s tvEnded EventPlaylist Array"preroll.mp4""areyoupopular.mp4""destinationearth.mp4"Now you might be tempted to look at the <video> markup specs to see how you specify a playlist, but for this you’re going to need code beca...

  • Page 402

    366 Chapter 8implementing a playlistImplementing Webville TV’s playlist<script src="webvilletv.js"></script>Now we’re going to use JavaScript and the video API to implement the Webville TV playlist. Let’s start by adding a link to a JavaScript file in webvilletv.html;...

  • Page 403

    you are here 4 367not your father’s tvNow we just need to write the handler for the video’s ended event. This handler is going to be called whenever the video player hits the end of the current video file. Here’s how we write the nextVideo function (add it to webvilletv.js):How to write th...

  • Page 404

    368 Chapter 8testing the playlistGood question.When we were using multiple source tags we could count on the browser to sort through one or more video formats and decide if it could play any of them. Now that we’re using code we’re just giving the video element a single option. So how do we ...

  • Page 405

    you are here 4 369not your father’s tvfunction getFormatExtension() { if (video.canPlayType("video/mp4") != "") { return ".mp4"; } else if (video.canPlayType("video/webm") != "") { return ".webm"; } else if (vid...

  • Page 406

    370 Chapter 8dealing with formats againwindow.onload = function() { playlist = ["video/preroll", "video/areyoupopular", "video/destinationearth"]; video = document.getElementById("video"); video.addEventListen...

  • Page 407

    you are here 4 371not your father’s tv You may need to install Quicktime to play mp4 video in Safari.Quicktime often comes installed by default, but if it’s not, you can download it from http://www.apple.com/quicktime/download/. Google Chrome has extra security restrictions.The...

  • Page 408

    372 Chapter 8our message to youI keep tellin’ you, it’s not just about JavaScript... you’ve gotta see the big picture. Building web apps is about markup, CSS, and JavaScript and its APIs. At some point we have to treat you like a real developer.In this book we’ve (hopefully) helped you e...

  • Page 409

    you are here 4 373not your father’s tvThis just in... we just got the contract to build the Starring You Video software for their new video booth. What on earth is that? Oh, just the latest HTML5-enabled video messaging booth—a customer enters an enclosed video booth and shoots their own vid...

  • Page 410

    374 Chapter 8checking out the starring you video boothBelow you’ll see our demo unit complete with a user interface. What we’ve got is a video screen where users will see their video played back. They’ll be able to apply a filter like “old-time western” or “sci-fi,” see how it look...

  • Page 411

    you are here 4 375not your father’s tv<!doctype html><html lang="en"><head> <title>Starring YOU video Booth</title> <meta charset="utf-8"> <link rel="stylesheet" href="videobooth.css"> <script src=&quo...;

  • Page 412

    376 Chapter 8looking at the existing codeSo let’s crack open the JavaScript (videobooth.js). It looks like all the interface buttons work, they just don’t do anything interesting, yet. But it’s important that we understand how these are set up because the buttons are going to invoke the co...

  • Page 413

    you are here 4 377not your father’s tvfunction handleControl(e) { var id = e.target.getattribute("id"); if (id == "play") { pushUnpushButtons("play", ["pause"]); } else if (id == "pause") { pushUnpushButtons("pause&q...;

  • Page 414

    378 Chapter 8setting up button handlersfunction setvideo(e) { var id = e.target.getattribute("id"); if (id == "video1") { pushUnpushButtons("video1", ["video2"]); } else if (id == "video2") { pushUnpushButtons("video2&...

  • Page 415

    you are here 4 379not your father’s tvAnd for the sake of completeness (or if you’re on a 11-hour flight to Fiji without Internet access and you really want to type all this in):And here are the helper functionsfunction pushUnpushButtons(idToPush, idarrayToUnpush) { if (idToPush != "...

  • Page 416

    380 Chapter 8an early testWe haven’t done much writing code, but we are reading and understanding code, and that can be just as good. So load the videobooth.html file into your browser and check out the buttons. Give them a good testing. For extra credit, add some alerts into the handler funct...

  • Page 417

    you are here 4 381not your father’s tvI think I missed something... how did you get from <div>s with anchor tags to having buttons in the interface?That would be the power of CSS.It’s a shame this book isn’t Head First HTML5 Programming with JavaScript & CSS, but then it would be...

  • Page 418

    382 Chapter 8exercise solutionAll the player controls use the handleControl handler.Radio buttons, play and pause can’t be selected at the same time.Loop and Mute are toggle buttons, they can be used independently of any other buttons.All these are radio buttons; we allow just one effect to be...

  • Page 419

    you are here 4 383not your father’s tvvar videos = {video1: "video/demovideo1", video2: "video/demovideo2"};window.onload = function() { var video = document.getElementById("video"); video.src = videos.video1 + getFormatExtension(); video.load(); var c...

  • Page 420

    384 Chapter 8supporting the custom video controlsImplementing the video controlsAlright, time to get to those buttons! Now, it’s important to point out that for this project, we’re going to implement our own video controls. That is, rather than use the built-in video controls, we’re going...

  • Page 421

    you are here 4 385not your father’s tvImplementing the rest of the video controlsLet’s knock out the rest of the controls—they’re so straightforward they’re almost going to write themselves:function handleControl(e) { var id = e.target.getattribute("id"); var video = do...

  • Page 422

    386 Chapter 8dealing with video ended eventTaking care of a loose end...There’s a little loose end we need to take care of to really make these buttons work like they should. Here’s the use case: let’s say you’re playing a video and you don’t have loop selected, and the video plays to ...

  • Page 423

    you are here 4 387not your father’s tvfunction setvideo(e) { var id = e.target.getattribute("id"); var video = document.getElementById("video"); if (id == "video1") { pushUnpushButtons("video1", ["video2"]); } else if (id == ...

  • Page 424

    388 Chapter 8video element interviewHead First: Welcome, Video. I’m going to jump right to the topic on everyone’s minds, and that would be YOU and the Canvas element.Video: Meaning?Head First: Allegedly nights out on the town, early morning breakfasts together. Need I say more?Video: What i...

  • Page 425

    you are here 4 389not your father’s tvIt’s time for special effectsIsn’t it about time we add those movie effects? What we want to do is take our original video and be able to apply effects, like film noir, western, and even an otherworldly sci-fi effect. But if you look at the video API, ...

  • Page 426

    390 Chapter 8plan for implementing video effects1We know we’ve still got to hook up those buttons that control the effects. So we’re going to do that first.2We’re going to learn a little about video processing and check out the “scratch buffer” technique for adding our effects.3We’re...

  • Page 427

    you are here 4 391not your father’s tvfunction setEffect(e) { var id = e.target.getattribute("id"); if (id == "normal") { pushUnpushButtons("normal", ["western", "noir", "scifi"]); effectFunction = null; } else ...

  • Page 428

    392 Chapter 8overview of video processingHow video processing worksWhat we’ve done so far is given ourselves a way to assign a function to the effectsFunction global variable as a result of clicking on the effects buttons in the interface. For now, just take that knowledge and tuck it in the b...

  • Page 429

    you are here 4 393not your father’s tvHow to process video using a scratch bufferBehindthe Scenes1The browser decodes the video into a series of frames. Each frame is a rectangle of pixels with a snapshot of the video at a given point in time. Now, you might ask why we’re using two canvases ...

  • Page 430

    394 Chapter 8using a scratch buffereffectFunction( )3We iterate over scratch buffer, pixel by pixel, passing each pixel to our effects function for processing.4After all the pixels in the scratch buffer are processed, we copy them from the scratch buffer canvas to the display canvas.5And the...

  • Page 431

    you are here 4 395not your father’s tvImplementing a scratch buffer with CanvasAs you already know, to implement a scratch buffer in canvas we need two canvases: one to do our computation in, and one to display our results. To create those canvases, we’ll start back in our HTML file videoboo...

  • Page 432

    396 Chapter 8implementing frame processingWriting the code to process the videoWe’ve got a video element, a buffer that’s a canvas, and a canvas that is going to display the final video frames. And we’ve also got them stacked on one another so we see only the top display canvas, which will...

  • Page 433

    you are here 4 397not your father’s tvbuffer.drawImage(video, 0, 0, bufferCanvas.width, displayCanvas.height);var frame = buffer.getImageData(0, 0, bufferCanvas.width, displayCanvas.height);var length = frame.data.length / 4;for (var i = 0; i < length; i++) { var r = frame.data[i * 4 + 0...

  • Page 434

    398 Chapter 8frame rates and timersWe wish we could.You’re absolutely right: what we’d love to do is have our handler called once for every frame, but the video API doesn’t give us a way to do that. It does give us an event named timeupdate that can be used to update a running time displa...

  • Page 435

    you are here 4 399not your father’s tvNow we need to write some effectsFinally, we’ve got everything we need to write the video effects: we’re grabbing each frame as it comes in, accessing the frame data pixel by pixel and sending the pixels to our effect filter function. Let’s look at t...

  • Page 436

    400 Chapter 8exercise in implementing video effectsThis book isn’t really about video processing and effects, but it sure is fun. Below we’ve got the western and sci-fi effects. Look through the code and make notes on the right as to how each works. Oh, and we added an extra one—what does ...

  • Page 437

    you are here 4 401not your father’s tvThis is it! We have this code wrapped up and ready to ship off to Starring You Video. Go ahead and double check that you’ve got all the code typed in, save, and load videobooth.html. Then have fun playing around with your new app!The Big Test DriveNormal...

  • Page 438

    402 Chapter 8IN THE LABORATORYObviously we’ve only scratched the surface in terms of video processing, and we’re sure you can think of more creative effects than those we came up with. Go ahead and think up a few, implement them, and document them here. Have you invented something really coo...

  • Page 439

    you are here 4 403not your father’s tvHey I know its almost the end of the chapter, but I keep meaning to ask this: we’ve been loading video from a local file, what changes if my video is hosted on the Web?Sure, just use a web URL.You can substitute a web URL for any of the sources we been d...

  • Page 440

    404 Chapter 8video streamingNo.There is no standard for streaming video with HTML5. As a matter of fact the problem isn’t HTML5, there isn’t really a supported standard for streaming video anywhere—but there are plenty of proprietary ones. Why? There are a number of reasons ranging from th...

  • Page 441

    you are here 4 405not your father’s tvBut it’s not: we have all those nasty network issues, incompatible devices and operating systems, and an increasing chance of asteroids hitting the earth. That last one we can’t help with, but for the first two actually knowing you have an error is hal...

  • Page 442

    406 Chapter 8handling video errorsDealing with errors is complex business and how you deal with errors depends a lot on your application, and what would be appropriate for the app and your users. That said, we can at least get you started and point you in the right direction. Let’s take Webvil...

  • Page 443

    you are here 4 407not your father’s tvThis is where it gets exciting, because think of all you know how to do with HTML markup, with the video element and, of course, the canvas...not to mention web services, geolocation... wow. Sure, we did some cool video processing with canvas, but you can ...

  • Page 444

    408 Chapter 8review of the video api ƒYou can play video by using the <video> element with a few simple attributes. ƒThe autoplay attribute starts playback on page load, but use only when appropriate. ƒThe controls attribute causes the browser to expose a set of playback controls. ƒThe...

  • Page 445

    you are here 4 409not your father’s tvHTML5crossBefore you sit back and watch some more Webville TV, do a quick crossword to make it all stick. Here’s your Chapter 8 crossword puzzle.123456789101112131415Across2. Type of delivery the video element uses for video.4. To provide several video o...

  • Page 446

    410 Chapter 8exercise solutionsThis book isn’t really about video processing and effects, but it sure is fun. Below we’ve got the western and sci-fi effects. Look through the code and make notes on the right as to how each works. Oh, and we added an extra one—what does it do? Here’s our ...

  • Page 447

    you are here 4 411not your father’s tvvIDEO RECONNaISSaNCE SOLUTIONvideoSafariChromeFirefoxMobile WebkitOperaIE9+IE8IE7 or <H.264WebMOgg TheoraBrowseriOS and Android devices (among others)someHTML5cross SolutionC1P2R O G R E3S SIV ENDTM4U L TIP L ERCS5C R A T C6HL7O O PA8U T O P L A YCOLTF9...

  • Page 448

    412 Chapter 8actionURI(https://freepdf-books.com /):www.freepdf-books.com actionURI(https://freepdf-books.com /):https://freepdf-books.com

  • Page 449

    this is a new chapter 413Web Storagestoring things locally9Tired of stuffing your client data into that tiny closet cookie? That was fun in the ’90s, but we’ve got much bigger needs today with web apps. What if we said we could get you five megabytes on every user’s browser? You’d probab...

  • Page 450

    414 Chapter 9history of browser storageHow browser storage works (1995 - 2010)Building a shopping cart? Need to store some user preferences for your site? Or just need to stash some data that you need to be associated with each user? That’s where browser storage comes in. Browser storage gives...

  • Page 451

    you are here 4 415storing things locallyBrowserWeb ServerCookies are sent back and forth in each HTTP request and response.Cookies are associated with a domain, like “pets-R-us.com” and are only sent to that domain. So, there is no way for “PetsEmporium.com” to get its hands on this cook...

  • Page 452

    416 Chapter 9how web storage worksCookies have been with us a long time, but you might be able to think of some ways they could be improved on.Check all the items below that you think make cookies problematic:There’s only 4k to work with, my app needs more storage than that.Sending the cookie ...

  • Page 453

    you are here 4 417storing things locallyBrowserBrowserlocalStoragelocalStorageHow HTML5 Web Storage worksHTML5 gives us a nice, simple JavaScript API in the browser for storing key/value pairs that are persistent. You’re not limited to four stingy kilobytes of storage either; all browsers toda...

  • Page 454

    418 Chapter 9using web storageNote to self...Pick up dry cleaningNeed a system for getting things done? It’s hard to improve on the old Post-it note system (more commonly known as stickies). You know how it works: you jot down your “to do” item, stick it somewhere, and once you’ve done t...

  • Page 455

    you are here 4 419storing things locallylocalStorage.setItem("sticky_1", "Cancel cable tv, who needs it now?");Another key. Like we said already, you can use any key you like as long as it is a string, but you can only store one value per key.A value to go with our new key. v...

  • Page 456

    420 Chapter 9how the local storage api worksSure. Here it is in a nutshell: your browser provides you with a local store—space on your own computer, in your browser—that a page can make use of to store key/value pairs. You created a few key/value pairs, stored them away using the local stora...

  • Page 457

    you are here 4 421storing things locallylocalStoragelocalStoragekey: “sticky_0”value: “Pick up dry cleaning”key: “sticky_0”value: “Pick up dry cleaning”Once you’ve placed the key/value pair in localStorage, it is persistently stored for you, even if you close the browser wind...

  • Page 458

    422 Chapter 9questions about local storageQ: First you said “Web Storage” and then you started talking about “local storage.” Are they the same?A: The Web standard is named “Web Storage” but most people just call it local storage (in fact, the browsers even expose the API through the...

  • Page 459

    you are here 4 423storing things locallyYou’ve got the right technology.It’s true, with localStorage you can only use strings as keys and values. But, that’s not as restricting as it sounds. Let’s say you need to store the integer 5. You can store the string “5” instead, and then con...

  • Page 460

    424 Chapter 9how local storage is like an arrayLocal storage has another side you haven’t seen yet. Not only does localStorage provide the getter and setter methods (that is, getItem and setItem), it also allows you to treat the localStorage object as an associative array. What does that mea...

  • Page 461

    you are here 4 425storing things locallyfunction shellGame() { localStorage.setItem("shell1", "pea"); localStorage.setItem("shell2", "empty"); localStorage.setItem("shell3", "empty"); localStorage["shell1"] = "...;

  • Page 462

    426 Chapter 9storage technologies chatTonight we have the incumbent browser storage technology, the “Cookie” along with the new front runner, Local Storage.Tonight’s talk: Cookie and Local StorageCookie:There he is, the golden boy, Local Storage. I’ve been in this business for over a dec...

  • Page 463

    you are here 4 427storing things locallyCookie:Yeah, I’m light, nimble, we might even say agile. Come on, I’m an open book, just pure storage to put whatever you want in. Oh, and key/value pairs are some great innovation? <Snicker> Oh yeah, and you store everything as a string! Ni...

  • Page 464

    428 Chapter 9the stickies appNow that you’ve had a little time to play with Web Storage, let’s take this implementation further. We’re going to create a Sticky Notes application so you can see your stickies and add new ones. Let’s take a peek at what we’re going to build before we bui...

  • Page 465

    you are here 4 429storing things locallyTo start, we need a way to enter the text of our sticky notes. And it would be great if we could see them in the page, so we need an element to hold all the notes in the page. Let’s work on some code to do that, starting with the HTML markup—take your ...

  • Page 466

    430 Chapter 9writing the stickies javascriptwindow.onload = init;function init() { for (var i = 0; i < localStorage.length; i++) { var key = localStorage.key(i); if (key.substring(0, 6) == "sticky") { var value = localStorage.getItem(key); addS...

  • Page 467

    you are here 4 431storing things locallyTime for another test drive!Go ahead and get this code into your script element and load it into your browser.Here’s what we got when we loaded the page in our browser:Now all we need to do is enable the form so we have a way to add new notes. To do that...

  • Page 468

    432 Chapter 9creating stickies with codefunction createSticky() { var value = document.getElementById("note_text").value; var key = "sticky_" + localStorage.length; localStorage.setItem(key, value); addStickyToDOM(value);}And the code to create a new sticky note:W...

  • Page 469

    you are here 4 433storing things locallyQ: Why do we test to see if each item’s key begins with the string “sticky”?A: Remember that all the pages from one domain (like apple.com) can see every item stored from other pages in that domain. That means if we aren’t careful about naming our ...

  • Page 470

    434 Chapter 9diagnosing browser storageWouldn’t it be great if there were a tool to directly view the items in your localStorage? Or a tool to delete items or even clear the whole thing out and start over when you are debugging? Well, all the major browsers ship with built-in developer tools t...

  • Page 471

    you are here 4 435storing things locally<!doctype html><html><head><title>Maintenance</title><meta charset="utf-8"><script>window.onload = function() { var clearButton = document.getElementById("clear_button"); clearButton.oncli...

  • Page 472

    436 Chapter 9a problem with stickiesAh, you’ve discovered a major design flaw.Alright, it’s time to come clean: we’ve built a great little app so far, and it should work perfectly for years to come as long as you don’t introduce any other items into the localStorage (like Joel did with h...

  • Page 473

    you are here 4 437storing things locallyPut a check next to the ways our current implementation could cause problems:Displaying stickies is inefficient if there are a lot of items in localStorage that aren’t stickies.It’s hard to quickly tell how many stickies there are; you have to iterate ...

  • Page 474

    438 Chapter 9storing arraysIf only I could store an array in localStorage. We could use it to hold all the keys of the stickies and we could also always easily know the number of stickies we’re storing. But we all know localStorage stores only strings, so even though an array would be dreamy, ...

  • Page 475

    you are here 4 439storing things locallyWe haven’t been lying, it is true that you can store only strings as the values of localStorage items, however that isn’t the whole truth because we can always convert an array (or an object) into a string before we store it. Sure, it seems like cheati...

  • Page 476

    440 Chapter 9rewriting stickies using an array Okay, we know roughly how we’re going to keep track of our stickies using an array, but let’s take this a little further and make sure we can iterate through and display all the stickies. In the current code we display all the stickies in the in...

  • Page 477

    you are here 4 441storing things locallyfunction init() { // button code here... var stickiesarray = localStorage["stickiesarray"]; if (!stickiesarray) { stickiesarray = []; localStorage.setItem("stickiesarray", (stickiesarray)); } els...

  • Page 478

    442 Chapter 9adding a unique idWhat needs to change?We have two things that need to change in createSticky. First, we need a new way to generate a key for each sticky that is unique. We also need to alter the code so that it stores the sticky in the stickiesArray in localStorage.Q: What are mill...

  • Page 479

    you are here 4 443storing things locallyPutting it all togetherIt’s time to integrate all this new array-based code, including the init and createSticky functions. To do that we’re first going to abstract a small bit of code that’s needed in both functions—it’s the code that retrieves ...

  • Page 480

    444 Chapter 9integrating all the codefunction init() { var button = document.getElementById("add_button"); button.onclick = createSticky; var stickiesarray = getStickiesarray(); for (var i = 0; i < stickiesarray.length; i++) { var key = stickiesarray[i]; va...

  • Page 481

    you are here 4 445storing things locallyTest Drive!Get all this code in and clear out your localStorage to make a nice clean start. Load this code, and you should see exactly the same behavior as last time. Joel, you’ll see your code working correctly now!Q: We’re using “sticky_” as the ...

  • Page 482

    446 Chapter 9another feature request: deleteIt’s hard to manage my busy life if I can’t get rid of these stickies after I’m done with them. Can you add a delete function?Deleting sticky notesShe’s right, this app isn’t going to be very successful if we can’t remove stickies. We’ve ...

  • Page 483

    you are here 4 447storing things locallyYour pseudo-code hereLet’s delete a sticky!Below you’ll see the contents of localStorage. You’ve got all the JavaScript you want along with the removeItem method. Using a pencil, sketch out what you need to do to remove sticky_1304220006342 from loca...

  • Page 484

    448 Chapter 9exercise solution(1) Remove the sticky with the key “sticky_1304220006342” from localStorage using the localStorage.removeItem method.(2) Get the stickiesArray.(3) Remove element with key=“sticky_1304220006342” from the stickiesArray.(4) Write stickiesArray back into localS...

  • Page 485

    you are here 4 449storing things locallyThe deleteSticky functionYou made a plan for how to delete the sticky notes, so let’s take a look at the deleteSticky function:I get the code, but I don’t see how we’re getting the key to pass to deleteSticky. Come to think of it, how is the user ch...

  • Page 486

    450 Chapter 9selecting stickies with html and javascriptHow do you select a sticky to delete?function addStickyToDOM(key, value) { var stickies = document.getElementById("stickies"); var sticky = document.createElement("li"); sticky.setattribute("id", key);...

  • Page 487

    you are here 4 451storing things locally<click><click>How to get the sticky to delete from the eventfunction deleteSticky(e) { var key = e.target.id; if (e.target.tagName.toLowerCase() == "span") { key = e.target.parentNode.id; } localStorage.removeItem(k...

  • Page 488

    452 Chapter 9deleting stickies from the domNice work! Now, can you give me a way to color code my stickies? You know yellow for urgent, blue for ideas, pink for backburner, that kind of thing?Okay, test it...Get all that code in, load the page, add and delete some stickies. Quit your browser, lo...

  • Page 489

    you are here 4 453storing things locallyRight now, all our notes are yellow. Wouldn’t it be nicer if we could have a whole range of sticky note colors? This is way better, don’t you think?We could add a selection menu up here so you can choose the color you want for your note.Update the user...

  • Page 490

    454 Chapter 9using json to store colorlocalStoragekey: “sticky_1304391836840”value: {“value”:”Cancel cable tv, who needs it now?”,”color”:”LightPink”}function createSticky() { var stickiesarray = getStickiesarray(); var currentDate = new Date(); var colorSelectObj =...

  • Page 491

    you are here 4 455storing things locallyfunction addStickyToDOM(key, stickyObj) { var stickies = document.getElementById("stickies"); var sticky = document.createElement("li"); sticky.setattribute("id", key); sticky.style.backgroundColor = stickyObj.colo...

  • Page 492

    456 Chapter 9testing color stickiesTest drive sticky note colorsBefore running the Note to Self app again, you’ll need to clear out your localStorage first because the previous version of our stickies didn’t have any color stored in them, and now we’re using a different format for our stic...

  • Page 493

    you are here 4 457storing things locallyI was thinking, if we can store objects and arrays, why don’t we just store all the notes in the array itself, why do we need all these other items? It seems to make it all complicated when it could just be embedded in one item in localStorage.For some u...

  • Page 494

    458 Chapter 9We’ve told you that you have five whole megabytes of storage on every user’s browser, but while five megabytes sounds like a lot, remember that all your data is stored in the form of a string rather than in a byte-efficient data format. Take a long number, say, the national debt...

  • Page 495

    you are here 4 459storing things locallyWe don’t see any reason not to push your browser to the limit, see what it’s made of, see how far it can go, see what its behavior is under pressure. Let’s write a little code to push your browser over its storage limit:<html><head><sc...

  • Page 496

    460 Chapter 9info about session storageI’ve been beta testing my shopping cart app and users don’t want their shopping cart sticking around in the browser. How can I remove all the shopping cart items when the user closes the browser? Did I choose the wrong technology?No Luke, there is anoth...

  • Page 497

    you are here 4 461storing things locallygetItemlengthQUOTA_EXCEEDED_ERRsetItemremoveItemkeyI take keys and values and write them into the localStorage. Now keep in mind if there’s an item with that key already in the localStorage, I’m not going to warn you, I’m just going to overwrite it s...

  • Page 498

    462 Chapter 9ways to use web storageNow that you know localStorage, how are you going to use it?I’m going to store playlists with metadata for my users. They’ll be able to store their favorite clips along with the timecode where they left off viewing.I’m using sessionStorage for my new eco...

  • Page 499

    you are here 4 463storing things locallyThis gives me a new way to store user state. I used to need some kind of server-side based session and backend storage. Now I can just store my users’ state locally, and bring in the server-side code only when I have to.I’ve got a really cool game that...

  • Page 500

    464 Chapter 9review of web storage ƒWeb Storage is a store in your browser and an API you can use to save and retrieve items from the store. ƒMost browsers provide at least 5 megabytes of storage per origin. ƒWeb Storage consists of local storage and session storage. ƒLocal storage is persis...

  • Page 501

    you are here 4 465storing things locallyHTML5crossTake some time to test your own local storage.12345678910111213Across3. When we used the _________ of localStorage to create key names, we ran into a problem: gaps in the names of our sticky notes.4. Luke Skywalker’s sister.7. We have to ______...

  • Page 502

    466 Chapter 9exercise solutionsfunction shellGame() { localStorage.setItem("shell1", "pea"); localStorage.setItem("shell2", "empty"); localStorage.setItem("shell3", "empty"); localStorage["shell1"] = "empty&qu...;

  • Page 503

    you are here 4 467storing things locallyfunction init() { // button code here... var stickiesarray = localStorage["stickiesarray"]; if (!stickiesarray) { stickiesarray = []; localStorage.setItem("stickiesarray", JSON.stringify(stickiesarray)); } else...

  • Page 504

    468 Chapter 9exercise solutionsWe’ve told you that you have five whole megabytes of storage on every user’s browser, but while five megabytes sounds like a lot, remember that all your data is stored in the form of a string rather than in a byte-efficient data format. Take a long number, say,...

  • Page 505

    you are here 4 469storing things locallyWe don’t see any reason not to push your browser to the limit, see what it’s made of, see how far it can go, see what its behavior is under pressure. Let’s write a little code to push your browser over its storage limit:<html><head><sc...

  • Page 506

    470 Chapter 9exercise solutionsgetItemlengthQUOTA_EXCEEDED_ERRsetItemremoveItemkeyI take keys and values and write them into the localStorage. Now keep in mind if there’s an item with that key already in the localStorage, I’m not going to warn you, I’m just going to overwrite it so you bet...

  • Page 507

    you are here 4 471storing things locallyHTML5cross SolutionS1P2L3E N G T HL4EI AIO5RP6CBSAKJS7T RI N G IF YRIEISSF8IV ECZT9A R G E TIS10E TIT E MEIJAS11T RI N G SNIA12R R A YTTRC13A T C HYAcross3. When we used the _________ of localStorage to create key names, we ran into a problem: gaps in the ...

  • Page 508

    actionURI(https://freepdf-books.com /):www.freepdf-books.com actionURI(https://freepdf-books.com /):https://freepdf-books.com

  • Page 509

    this is a new chapter 473putting javascript to work10Web WorkersSlow script—do you want to continue running it? If you’ve spent enough time with JavaScript or browsing the Web you’ve probably seen the “slow script” message. And, with all those multicore processors sitting in your new ...

  • Page 510

    474 Chapter 10javascript threadsThe Dreaded Slow ScriptOne of the great things about JavaScript is it does only one thing at a time. It’s what we like to call “single-threaded.” Why’s that great? Because it makes programming straightforward. When you have lots of threads of execution hap...

  • Page 511

    you are here 4 475putting javascript to workProcess an array of dataUpdating the DOMFetching form dataYikes, processing a big array is taking a lot of time!Handling another user clickValidating user inputWhat’s going on up there? Things aren’t getting done!Who’s hogging all the processing ...

  • Page 512

    476 Chapter 10javascript web workersAdding another thread of control to helpBefore HTML5, we were stuck with one thread of control in our pages and apps, but with Web Workers we’ve now got a way to create another thread of control to help out. So, if you’ve got code that takes a long time to...

  • Page 513

    you are here 4 477putting javascript to workJavaScript Exposed (Again)This week’s interview:Where JavaScript spends his time.Head First: Welcome back JavaScript, great to have you.JavaScript: Glad to be here, as long as we stick to my schedule, lots to do.Head First: That is actually where I t...

  • Page 514

    478 Chapter 10how web workers workHow Web Workers workBrowserLet’s take a look at a day in the life of a Web Worker: how workers are created, how they know what to do, and how they get results back to your main browser code.To use Web Workers, the browser first has to create one or more worker...

  • Page 515

    you are here 4 479putting javascript to workBrowserTo get a worker to start working, the browser typically sends it a message. The worker code receives the message, takes a look at it to see if there are any special instructions, and starts working.WorkerWhen the worker completes its work, it th...

  • Page 516

    480 Chapter 10dom accessWhy not allow workers to access the DOM? I mean this seems like a lot of trouble to pass messages back and forth when all of these workers are running in the same browser.To keep things efficient. One reason the DOM and JavaScript have been so successful is that we’re ...

  • Page 517

    you are here 4 481putting javascript to workTake a look at all the potential uses for workers below. Which ones might improve the design and the performance of an app?Caching data for use in your pages.Spell checking the page as the user types.Processing large amounts of data in arrays or large ...

  • Page 518

    482 Chapter 10watch out for browser support Almost all the modern browsers support Web Workers, but there is one exception: Internet Explorer 9. The good news is that for IE10 and later, you can count on Web Workers, but with IE9 and all the IE versions before it, you’ll have to suppl...

  • Page 519

    you are here 4 483putting javascript to workYour first Web Worker...Let’s get down to the business of creating a worker to see how this all works. To do that we need a page to put everything in. We’ll go with the simplest HTML5 markup we can get away with; type this into pingpong.html:Have h...

  • Page 520

    484 Chapter 10writing a worker managerNow that you know how to create a worker (and how easy it is), let’s start working on our manager.js code. We’ll keep this code simple and create just one worker for now. Create a file named manager.js and add this code:Writing Manager.jsAnd we’re usin...

  • Page 521

    you are here 4 485putting javascript to workReceiving messages from the workerWe’re not quite done with our manager.js code yet—we still need to be able to receive a message from the worker if we’re going to make use of all its hard work. To receive a worker’s message we need to define a...

  • Page 522

    486 Chapter 10your first workerWriting the worker’s message handleronmessage = pingPong;function pingPong(event) { if (event.data == "ping") { postMessage("pong"); }}When the worker receives a message from the main code, the pingPong function will be called, an...

  • Page 523

    you are here 4 487putting javascript to workMake sure you’ve got pingpong.html, manager.js and worker.js typed in and saved. Now keep those files open so you can review them and let’s think through how this works. First, manager.js creates a new worker, assigns a message handler to it, and t...

  • Page 524

    488 Chapter 10BE the BrowserIt’s time to pretend you’re the browser evaluating JavaScript. For each bit of code below, act like you’re the browser and write its output in the lines provided. You can assume this code is using the same worker.js we just wrote:window.onload = function() { ...

  • Page 525

    you are here 4 489putting javascript to workwindow.onload = function() { var worker = new Worker("worker.js"); worker.onmessage = function(event) { alert("Worker says " + event.data); } setInterval(pinger, 1000); function pinger() { worker.pos...

  • Page 526

    490 Chapter 10exercise to use compact workerquote.html<!doctype html><html lang="en"> <head> <title>Quote</title> <meta charset="utf-8"> </head><body> <p id="quote"></p> <script> ...

  • Page 527

    you are here 4 491putting javascript to workwindow.onload = function() { var numWorkers = 3; var workers = []; for (var i = 0; i <; i++) { var worker = new("worker.js"); worker. = function(event) { alert(event.target + " says " ...

  • Page 528

    492 Chapter 10including javascript code in a workerwindow.onload = function() { var numWorkers = 3; var workers = []; for (var i = 0; i < numWorkers; i++) { var worker = new Worker("worker.js"); worker.onmessage = function(event) { alert(event....

  • Page 529

    you are here 4 493putting javascript to workTake a look at importScripts.Web Workers have a global function named importScripts that you can use to import one or more JavaScript files into your worker. To use importScripts just give it a comma separated list of files or URLs you’d like to impo...

  • Page 530

    494 Chapter 10the mandelbrot setVirtual Land GrabExplorers of the Mandelbrot Set have already grabbed areas of the virtual countryside and given them names like the lovely “Seahorse Valley,” “Rainbow Islands,” and the dreaded “Black Hole.” And given the value of physical real estate...

  • Page 531

    you are here 4 495putting javascript to workWell, if you happen to be a mathematician then you know the Mandelbrot Set is the equation:and that it was discovered and studied by Benoit Mandelbrot. You also know that it’s simply a set of complex numbers (numbers with a real part, and an imaginar...

  • Page 532

    496 Chapter 10computing fractalsfor (i = 0; i < numberOfRows; i++) { var row = computeRow(i); drawRow(row);}How to compute a Mandelbrot SetLet’s take a look at how you’d typically structure your code to compute a Mandelbrot Set before we get workers involved. We don’t want to foc...

  • Page 533

    you are here 4 497putting javascript to workHow to use multiple workersYou already know how to create new workers, but how do you use them to do something a little more complicated, like computing the rows of the Mandelbrot Set? Or applying a Photoshop-like effect over an image? Or ray tracing a...

  • Page 534

    498 Chapter 10how to compute with workersNext, the browser code doles out a different part of the image for each worker to compute:The first region of the image is mine!The browser hands out pieces of the image to be computed by each worker.WorkerWorkerWorkerWorkerWorker12345I’ve got 2!3 here!...

  • Page 535

    you are here 4 499putting javascript to workAll the pieces of the image created by the workers are aggregated into the final image.WorkerWorkerWorkerWorkerWorkerAs pieces of the image come back from the workers they are aggregated into the image in the browser, and if there are more pieces to co...

  • Page 536

    500 Chapter 10how workers improve applicationsWhat does it matter if I break up the task and distribute it to workers? I mean, my computer still has the same CPU, how could the computation get any faster?It can be faster in two ways... First consider an application that has a lot of “computing...

  • Page 537

    you are here 4 501putting javascript to workIn theory, not in practice. Web Workers aren’t intended to be used in large numbers—while creating a worker looks simple in code, it requires extra memory and an operating system thread, which can be costly in start-up time and resources. So, in ge...

  • Page 538

    502 Chapter 10exercise your brain doing some code designfor (i = 0; i < numberOfRows; i++) { var taskForRow = createTaskForRow(i); var row = computeRow(taskForRow); drawRow(row);}Here’s our pseudo-code now, what do you need to do to add Web Workers?You’ve certainly got a lot of b...

  • Page 539

    you are here 4 503putting javascript to workLet’s build the Fractal Explorer appHere’s what we need to do:Creating the Fractal Viewer HTML MarkupFirst we need to set up an HTML page to hold our app. You’ll want to create an HTML file named fractal.html and add the following markup. Let’s...

  • Page 540

    504 Chapter 10ready bake fractal codeWe have to tell you we were planning on an entire chapter on the wonders of computing the Mandelbrot Set... we planned to explain it to you in detail, including a history of Benoit Mandelbrot, how he discovered it, all its amazing properties, pixel optimizati...

  • Page 541

    you are here 4 505putting javascript to workfunction makePalette() { function wrap(x) { x = ((x + 256) & 0x1ff) - 256; if (x < 0) x = -x; return x; } for (i = 0; i <= this.max_iter; i++) { palette.push([wrap(7*i), wrap(5*i), wrap(11*i)]); }}functio...

  • Page 542

    506 Chapter 10ready bake fractal codeReady Bake Code Continued...function setupGraphics() { canvas = document.getElementById("fractal"); ctx = canvas.getContext("2d"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var width = ((i_max - i...

  • Page 543

    you are here 4 507putting javascript to workfunction computeRow(task) { var iter = 0; var c_i = task.i; var max_iter = task.max_iter; var escape = task.escape * task.escape; task.values = []; for (var i = 0; i < task.width; i++) { var c_r = task.r_min + (task.r_max - ...

  • Page 544

    508 Chapter 10how to manage workers and tasksI’m idleI’m idleI’m idleI’m idleI’m idleI’m idleI’m idleWorkerWorkerWorkerWorkerWorkerWorkerWorkerWorkerI’m idleWith the Ready Bake Code out of the way, let’s now turn our attention to writing the code that is going to create and han...

  • Page 545

    you are here 4 509putting javascript to workWriting the codeNow that we know how we’re going to create and manage our workers, let’s write the code. We really need an initial function for this, so let’s create a function in mandel.js named init—we’ll place a few other things in it as w...

  • Page 546

    510 Chapter 10starting your fractal workersGetting the workers startedOkay we’ve got a few things to knock out: we need to start the workers, we need to write the function that can process the work that comes back from the workers and, well, we need to write the code for the worker too. Let’...

  • Page 547

    you are here 4 511putting javascript to workimportScripts("workerlib.js");onmessage = function (task) { var workerResult = computeRow(task.data); postMessage(workerResult);}We’re using importScripts to import the workerlib.js Ready Bake Code so the worker can call the computeRo...

  • Page 548

    512 Chapter 10close up on fractal tasksA little pit stop...That was a lot of code in just a few pages. Let’s take a quick pit stop, and refuel our tanks and stomachs. We also thought you might want to get a quick peek behind the scenes and see what the worker tasks and results look like (they ...

  • Page 549

    you are here 4 513putting javascript to workvar workerResult = computeRow(task.data);postMessage(workerResult);And what about the results we get from computing the row in the worker?What does this look like? Remarkably similar to the task:workerResult = { row: 1, width: 1024, generation...

  • Page 550

    514 Chapter 10processing worker resultsfunction processWork(worker, workerResults) { drawRow(workerResults); reassignWorker(worker);}We hand the results to drawRow to draw the pixels to the canvas.And our worker is all free, so we can reassign it to another task. To do that let’s write a...

  • Page 551

    you are here 4 515putting javascript to workEnough code already! Let’s road test this thing. Load the fractal.html file into your browser and see your workers going to work. Depending on your machine, your Fractal Explorer should run a little faster than before.We haven’t written any code to...

  • Page 552

    516 Chapter 10testing and improvementsfunction handleClick(x, y) { var width = r_max - r_min; var height = i_min - i_max; var click_r = r_min + width * x / canvas.width; var click_i = i_max + height * y / canvas.height; var zoom = 8; r_min = click_r - width/zoom; r_max = cli...

  • Page 553

    you are here 4 517putting javascript to workfunction resizeToWindow() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; var width = ((i_max - i_min) * canvas.width / canvas.height); var r_mid = (r_max + r_min) / 2; r_min = r_mid - width/2; r_max = r_mid + ...

  • Page 554

    518 Chapter 10managing fractal generationsThe anal-retentive chef coderThere’s just one more thing, and we could let this one go, but the code just doesn’t seem correct without it. Think through this with us: you’ve got a bunch of workers happily working on their rows and all of the sudden...

  • Page 555

    you are here 4 519putting javascript to workThat’s it! You should be ready to go with all your code. Load the fractal.html file into your browser and see your workers going to work. This version should be faster and more responsive than the original, single-threaded version; if you’ve got mo...

  • Page 556

    520 Chapter 10IN THE LABORATORYOur machine with eight cores. One core is maxed out and can’t compute any harder. The other seven are doing nothing to help.Now our eight cores are really working hard, and our fractal computation is WAY faster.We have eight cores in our machine, and so in the Fr...

  • Page 557

    you are here 4 521putting javascript to workPASTE YOUR NEW LOCATION IN THE MANDELBROT SET HEREYou’ve done it! You’ve got a fully functional Fractal Explorer that’s all ready for exploring the Mandbelbrot territory. So what are you waiting for—dig in and find your little slice of the vir...

  • Page 558

    522 Chapter 10more worker api functionalityHandle errors in workersworker.onerror = function(error) { document.getElementById("output").innerHTML = "There was an error in " + error.filename + " at line number " + error.lineno + ": "...;

  • Page 559

    you are here 4 523putting javascript to workUse importScripts to make a JSONP requestfunction makeServerRequest() { importScripts("http://SomeServer.com?callback=handleRequest");} function handleRequest(response) { postMessage(response);} makeServerRequest();You can’t i...

  • Page 560

    524 Chapter 10review of web workers ƒWithout Web Workers, JavaScript is single-threaded, meaning it can do only one thing at a time. ƒIf you give a JavaScript program too much to do, you might get the slow script dialog. ƒWeb Workers handle tasks on a separate thread so your main JavaScript c...

  • Page 561

    you are here 4 525putting javascript to workHTML5crossWow, Chapter 10; you’ve done it. Sit back, relax and make it stick by working the rest of your brain a little. Here’s your Chapter 10 crossword puzzle.12345678910111213141516Across4. You can pass ______ to workers using postMessage.8. Cap...

  • Page 562

    526 Chapter 10exercise solutionsBE the Browser SolutionIt’s time to pretend you’re the browser evaluating JavaScript. window.onload = function() { var worker = new Worker("worker.js"); worker.onmessage = function(event) { alert("Worker says " + event.data); ...

  • Page 563

    you are here 4 527putting javascript to workIn our HTML, we have a script that creates a worker, which executes immediately. The worker chooses a quote randomly from the quotes array, and sends the quote to the main code using postMessage. The main code gets the quote from event.data and adds it...

  • Page 564

    528 Chapter 10exercise solutionsHTML5cross SolutionL1OI2T3O4B J E C T SMHAPRT5C6N7M8U L TI C O R EEO9N M E S S A G ESRARMWM10TTD11O MP12I N G P O N GEOSILSRCM13A N D E L B R O TSARAXM14A N A G E RITGEPS15E A H O R S EETSJ16A M E S H E N S T RI D G EAcross4. You can pass ______ to workers using p...

  • Page 565

    you are here 4 529putting javascript to workWouldn’t it be dreamy if this were the end of the book? If there were no bullet points or puzzles or JavaScript listings or anything else? But that’s probably just a fantasy...Congratulations!You made it to the end.Of course, there’s still an app...

  • Page 566

    actionURI(https://freepdf-books.com /):www.freepdf-books.com actionURI(https://freepdf-books.com /):https://freepdf-books.com

  • Page 567

    this is a new chapter 531Appendix: leftoversThe Top Ten Topics (we didn’t cover)We’ve covered a lot of ground, and you’re almost finished with this book. We’ll miss you, but before we let you go, we wouldn’t feel right about sending you out into the world without a littl...

  • Page 568

    532 Appendixmodernizr and audio#1 ModernizrOne thing you’ve probably noticed in this book, is that when you want to detect browser support for an API, there is no uniform way of doing so; in fact, almost every API is detected in a different way. For geolocation, for instance, we look for the g...

  • Page 569

    you are here 4 533leftovers#2 AudioHTML5 gives you a standard way to play audio in your pages, without a plug-in, with the <audio> element:In addition to the <audio> element, there is also a corresponding Audio API that supports the methods you’d expect, like play, pause and load. ...

  • Page 570

    534 AppendixjQuery#3 jQueryjQuery is a JavaScript library that is aimed at reducing and simplifying much of the JavaScript code and syntax that is needed to work with the DOM, use Ajax and add visual effects to your pages. jQuery is an enormously popular library that is widely used and expandabl...

  • Page 571

    you are here 4 535leftoversThat’s really just the beginning; we can just as easily set the click handler on every anchor on the page: $(function() { $("a").click(function() { alert("I want to buy now!"); }); });To do that, all we need to do is us...

  • Page 572

    536 AppendixXHTML and SVG#4 XHTML is dead, long live XHTMLWe were pretty tough on XHTML in this book, first with the “XHTML is dead” discussion, and then later with “JSON versus XML”. The truth is, when it comes to XHTML, it is only XHTML 2 and later that has died, and in fact, you can w...

  • Page 573

    you are here 4 537leftovers#5 SVGScalable Vector Graphics, or SVG, is another way—aside from canvas—of including graphics natively in your web pages. SVG has been around a while (since 1999 or so) and is now supported in all the current versions of major browsers, including IE9 and later. Un...

  • Page 574

    538 Appendixoffline web apps and web sockets#6 Offline web appsIf you’ve got a smartphone or tablet, you’re probably accessing the Web on the go, and with WiFi and cellular networks, you’re connected almost all the time. But what about those times when you’re not? Wouldn’t it be great ...

  • Page 575

    leftovers 539#7 Web SocketsWe looked at two ways of communicating in this book: XMLHttpRequest and JSONP. In both cases we used a request/response model based on HTTP. That is, we used the browser to make a request for the initial web page, CSS and JavaScript, and each time we needed something...

  • Page 576

    540 Appendixmore canvas api#8 More canvas APIWe had fun with the canvas in Chapter 7, building our TweetShirt startup. But there are lots of other fun canvas-related things you can do and we wanted to touch on a few more of them here. We mentioned very briefly that you can save and restore the c...

  • Page 577

    you are here 4 541leftoversvar canvas = document.getElementById("canvas");var context = canvas.getContext("2d");var degrees = 36;context.save();context.translate(200, 200);context.fillStyle = "rgba(50, 50, 50, .5)";for (var i = 0; i < 360/degrees; i++) { context...

  • Page 578

    542 Appendixselectors api and more#9 Selectors APIYou already know how to select elements from the DOM using document.getElementById; we’ve used it throughout this book as a way to get HTML and JavaScript working together. You’ve also seen how to use document.getElementsByTagName (this metho...

  • Page 579

    you are here 4 543leftovers#10 But, there’s even more!Indexed Database API and Web SQLOkay, we really wanted to keep it to the ten things we didn’t tell you, but it looks like we’ve got a ways to go, and instead of standing between you and your reading of the index, we’re going to give y...

  • Page 580

    544 Appendixhtml5 guide to new constructionI can’t believe the book is almost over. Before you go, we’ve got a little parting gift for you from the City of Webville; it’s the guide to the HTML5 elements (and what’s new in CSS3) that we promised you. Isn’t Webville great?!actionURI(htt...

  • Page 581

    you are here 4 545leftoversHere in Webville we’ve recently made a few additions to our building codes and we’ve prepared a handy guide to any new construction you might be considering. In particular we’ve added a bunch of new new semantic elements that give you even more power to architect...

  • Page 582

    546 Appendixhtml5 semantic elements<section>A <section> is a “generic document”. You could use <section> to mark up, oh, say a Guide to HTML. Or to enclose the HTML for a game. A <section> is not a generic container—that’s <div>’s job. And remember, use &l...;

  • Page 583

    you are here 4 547leftovers<nav><nav> is navigation and for links, of course. But not just any links: use <nav> when you have a group of links, like navigation for your site, or a blogroll. Don’t use it for single links in paragraphs.<aside><aside> is handy for al...

  • Page 584

    548 Appendixcss3 propertiesWebville Guide to CSS3 PropertiesNow that you’ve got your new building blocks into place, it’s time to think about some interior design. You’ll want to make all your new construction look good, right?Adding style to your new construction with CSS3New propertiesTh...

  • Page 585

    this is the index 549IndexSymbols$ (dollar sign)$( ) (jQuery function) 570,534beginning JavaScript variable names 76,40, 78,422D drawing context, canvas 328, 292. See also Canvas API; context, canvasdefined 329, 293getting 338, 302, (comma), separating object properties 168,132{ } (cur...

  • Page 586

    550 Indexthe indexappendChild methodelement object 194,158in addStickyToDOM function (example) 486,450ul object method 137,101Apple’s HTTP Live Streaming 440,404application/xhtml+xml MIME type 572,536arc method, canvas context 349, 313direction, startAngle, and endAngle parameters ...

  • Page 587

    you are here 4 551the indexparsing HTML and building DOM from it 93,57, 117,81running code stored in local storage 140, 104same origin policy on video 444, 408security policy 280,244storing data using localStorage 144, 108support for HTML5 53, 17support for offline web apps 574, 538sup...

  • Page 588

    552 Indexthe index<canvas> elementadding border using CSS 324,288adding to web page 322, 286cubicle conversation about the <canvas> element 321,285partnership with <video> element 375, 339, 424,388case sensitivity in JavaScript 77,41cell phone triangulation 205,169ch...

  • Page 589

    you are here 4 553the indexconditionals 73, 37testing in while and for loops 83,47while loops 82, 46constructors 182,146, 196,160built-in 187, 151creating 183, 147LatLong constructor from Google Maps 219,183Map constructor from Google Maps 220,184Movie constructor function 186,150...

  • Page 590

    554 Indexthe indexdegradation, graceful 55,19degreesangles measured in 352,316converting to radians 353,317latitude and longitude in, converting to decimal values 203,167degreesToRadians function 216, 180, 353,317, 355,319, 380,344deleteSticky function (example) 485,449event object...

  • Page 591

    you are here 4 555the indexEeffectFunctioncalling to apply video filter 433,397used as variable to hold video filter function 427, 391effects 446,410applying to videos 425,389–391choice of, video booth 414, 378creating using canvas context translate and rotate methods 577,541writing...

  • Page 592

    556 Indexthe indexeventsanchor click event 412,376button click event 126, 90, 127,91, 128,92, 129,93cache, notification of 574,538canvas click event 383, 347, 419,383, 551,515dragstart and dragend events 579, 543image load event 369,333properties for event handlers in objects 190,...

  • Page 593

    you are here 4 557the indexfilm noir video filter 410,374, 435,399Firefox. See also browsersHTML5 support 54,18Ogg/Theora video 393,357.ogv video files 388,352WebM/VP8 video 393, 357Fireside ChatsCookie and Local Storage 462,426XMLHttpRequest and JSONP 296, 260firstChild property, e...

  • Page 594

    558 Indexthe indexfunctions, continuedSharpen Your Pencil exercise 158,122, 198,162using as values 165,129as values 164,128variables defined in 159, 123, 196,160Ggeneration, fractal (example) 554,518geolocation 201,165–212accuracy of location 227,191adding a Google marker to you...

  • Page 595

    you are here 4 559the indexrunning when user clicks button 129,93handleClick function (example) 551, 515, 552,516handleControl function (example) 413,377, 420,384implementing rest of video controls 421, 385handleRefresh function (example) 301, 265, 303,267, 308,272adding lastreporttim...

  • Page 596

    560 Indexthe indexintegersconversions to floating point numbers in expressions 81,45converting from strings 459, 423storing in localStorage as strings 459,423interface transformations on elements, using jQuery 571, 535Internet Explorer. See also browserscanvas support, versions 9 and later...

  • Page 597

    you are here 4 561the indexpopulating playlist items using an array 101,65, 118,82reworking handleButtonClick function 130, 94statements 80, 44, 113,77using setInterval in web applications 302,266single-threaded model 510, 474, 513,477summary of important points 111, 75syntax 75, 39t...

  • Page 598

    562 Indexthe indexLinuxApache server, configuring MIME types 407,371setting up server on 267, 231listsadding songs to playlist with JavaScript (example) 101, 65, 118,82creating <li> elements 135,99filling in items using array (example) 105, 69finding all child <li> elements o...

  • Page 599

    you are here 4 563the indexMMacApache server, configuring MIME types 407,371setting up server on 267, 231task monitor on OS X 556, 520makeImage function (example) 383, 347makeServerRequest function (example) 559, 523Mandelbrot, Benoit 531, 495Mandelbrot Set. See also Fractal Explorer appl...

  • Page 600

    564 Indexthe index.mp4 video files 388, 352MP4 container 393, 357MPEG-LA group 393, 357multi-core processors 536,500muted property, video object 421, 385Nnamesof functions 157, 121guide to better naming of variables 78, 42local and global variables with same name 162,126localStorage ke...

  • Page 601

    you are here 4 565the indexopen event, Web Sockets 575, 539Opera. See also browsersHTML5 support 54,18not supporting XMLHttpRequest Level 1 277,241Ogg/Theora video 393,357.ogv video files 388,352WebM/VP8 video 393, 357<option> element, in stickies application form 489, 453option...

  • Page 602

    566 Indexthe indexpostMessage methodWeb Sockets 575,539worker object 520,484, 547,511, 548,512<p> (paragraph) elements, changing using JavaScript 98,62preload attribute, <video> element 390, 354presentation, separate from content, in canvas 362, 326previewHandler function (...

  • Page 603

    you are here 4 567the indexscope, variables 160,124scratch buffer, video processing with 426,390, 429,393implementing buffer with canvas 431, 395–398<script> elements 63,27adding to HTML file for call to Twitter JSONP API 358,322adding to HTML in <head> or <body> 8...

  • Page 604

    568 Indexthe indexsrc attribute<script> element 89, 53, 254,218, 285,249updating with setAttribute 303,267<source> element 394,358, 395,359<video> element 389,353, 390,354src propertyaudio object 569, 533image object 369,333video object 406,370startWorkers funct...

  • Page 605

    you are here 4 569the indextimeDate object, getTime method 478,442milliseconds since 1970 478, 442<time> element 583, 547timeout option 235,199, 237,201timestamp property, position object 226, 190timeupdate event 434, 398title property, document object 193,157toDataURL method, c...

  • Page 606

    570 Indexthe indexvideo, continuedgetting demo videos ready 419, 383helper functions 415,379implementing video controls 420, 384–386overview of video processing 428, 392setEffect and setVideo handlers 414,378switching test videos 423,387video processing using scratch buffer 429,393w...

  • Page 607

    you are here 4 571the indexReady Bake Code not working in some browsers 140,104security restrictions in Chrome preventing running of Web Workers from file 518, 482server required to test geolocation code on mobile devices 215, 179work around for browsers not supporting XML-HttpRequest's onlo...

  • Page 608

    572 Indexthe index“Wherever you go, there you are.” (Geolocation example) 228,192while loops 82,46deciding between for loops and 83, 47evaluating (example) 84, 48example in JavaScript 62,26if/else statements in 86,50white space in JavaScript code 75, 39width and height attributes&...

  • Page 609

    you are here 4 573getting to know HTML5All interior layouts were designed by Eric Freeman and Elisabeth Robson. Kathy Sierra and Bert Bates created the look & feel of the Head First series. The book was produced using Adobe InDesign CS and Adobe Photoshop CS. The book was typeset using Uncl...

  • Page 610