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...
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...
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...
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...
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...
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...
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...
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 ...
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
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...
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...
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 ...
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...
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...
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...
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,...
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...
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...
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...
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’...
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 ...
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,#...
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....
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...
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...
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...
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 ...
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...
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 ...
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...
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). ...
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...
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...
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...
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...
actionURI(https://freepdf-books.com /):www.freepdf-books.com actionURI(https://freepdf-books.com /):https://freepdf-books.com
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...
<!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> <...;
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 ...
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 ...
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 ...
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. ...
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...
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...;
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...
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 ...
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...
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...
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 ...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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 ...
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 ...
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 ...
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...
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...
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...
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...
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 ...
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...
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...
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...
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...
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 ...
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...
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...
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...
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...
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...
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 ...
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...
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...
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...
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...
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...
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;...
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...
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 ...
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 = _______________...
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...
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...;
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...
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 ...
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...
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>...
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....
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...
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 ...
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...
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...
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 ...
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...
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...
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...
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...
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...
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...
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...
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...
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....
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...
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....
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...
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...
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;...
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 =...
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...
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 = _______________...
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...
82 Chapter 2exercise solutions<!doctype html><html lang="en"><head> <title>My Playlist</title> <meta charset="utf-8"> <script> ____________ addSongs() { var song1 = document.______________("________"); var _____ = ...
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...
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...
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 ...
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...
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...
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...
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...
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...
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’...
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 ...
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...
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...
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...
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...
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 ...
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...
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 ...
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 ...
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("...
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...
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...
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...
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...
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...
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 ...
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...
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...
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 ...
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....
actionURI(https://freepdf-books.com /):www.freepdf-books.com actionURI(https://freepdf-books.com /):https://freepdf-books.com
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�...
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...
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...
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...
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...
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...
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 ...
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) { /...
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...
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...
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 ...
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...
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...
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...
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...
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 ...
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!")...
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 ...
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...
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...
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�...
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. �...
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...
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...
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 ...
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...
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", ...
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...
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 ...
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�...
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 ...
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...
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"...;
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,...
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...
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...
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...
150 Chapter 4a movie constructorfunction _____________(_________, __________, rating, showtimes) { this.title = _________; this.genre = genre; this.________________ = rating; this.showtimes = ________________; this.getNextShowing = function() { var now = new Date().getTime(...
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...
152 Chapter 4exercise solutionfunction ____________(___________, ____________, rating, showtimes) { this.title = ___________; this.genre = genre; this.________________ = rating; this.showtimes = ________________; this.getNextShowing = function() { var now = new Date().getTi...
you are here 4 153javascript functions and objectsvar banzaiMovie = new Movie("Buckaroo Banzai", "Cult Classic", 5, ["1:00pm", "5:00pm", "7:00pm", "11:00pm"...;
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...
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...
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 ...
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...
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...
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 ...
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...
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...
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...
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...
actionURI(https://freepdf-books.com /):www.freepdf-books.com actionURI(https://freepdf-books.com /):https://freepdf-books.com
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...
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...
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...
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...
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...
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...
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...
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...
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...
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 (...
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...
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...
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...
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 ________________________...
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...
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 ...
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...
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...
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 ...
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...
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...
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...
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...
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 ...
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...
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...
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...
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...
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...
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...
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�...
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...
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...
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...
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 ...
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...
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...
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...
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, ...
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...
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...
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...;
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...
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 _________...
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...
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...
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...
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...
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...
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...
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....
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...
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...
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...
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...
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...
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...
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...
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 ...
224 Chapter 6exercise solutionwindow.onload = function () { var url = "http://wickedlysmart.com/ifeelluckytoday"; var request = ______________________ ____________________________ { if (________________________) { displayLuck(_______________________); ...
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...
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...
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 ...
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�...
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 =...
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 ...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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�...
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 ...
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...
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...
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...
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�...
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...
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 ...
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: ...
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...
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="...;
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...
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...
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...
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...
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...
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...
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 ...
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 ...
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...
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...
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 ...
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() { ...
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...
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...
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...
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...
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...
you are here 4 275talking to the webfunction handleRefresh() { var url = "http://gumball.wickedlysmart.com" + "?callback=updateSales" + "&lastreporttime=" + lastReportTime + "&random=" + (new Date())....
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...
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...
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. ...
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...
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 ____...
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 ...
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...
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�...
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...
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...
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...
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=...
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...;
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...
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...
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:...
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...
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...
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...
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...
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...
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...
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...
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 ...
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&...
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...
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...
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...
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...
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,...
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...
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...
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...
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...
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 ...
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...
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...
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...
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...
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 ...
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...
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...
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...
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...
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...
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...
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, ...
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...
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...
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...
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...
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._______...
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...
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...
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...
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...
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...
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 ...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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&...
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...
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...
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() { ...
actionURI(https://freepdf-books.com /):www.freepdf-books.com actionURI(https://freepdf-books.com /):https://freepdf-books.com
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...
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...
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...
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 ...
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...
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...
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...
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,...
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...
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...
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...
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...
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...
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...
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 ...
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...
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...
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;...
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...
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 ...
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...
370 Chapter 8dealing with formats againwindow.onload = function() { playlist = ["video/preroll", "video/areyoupopular", "video/destinationearth"]; video = document.getElementById("video"); video.addEventListen...
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...
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...
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...
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...
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...;
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...
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...;
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&...
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 != "...
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...
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...
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...
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...
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...
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...
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 ...
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 == ...
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...
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, ...
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...
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 ...
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...
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 ...
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...
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...
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...
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...
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...
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...
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 ...
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...
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...
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...
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...
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...
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...
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 ...
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...
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...
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 ...
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...
412 Chapter 8actionURI(https://freepdf-books.com /):www.freepdf-books.com actionURI(https://freepdf-books.com /):https://freepdf-books.com
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...
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...
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...
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 ...
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...
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...
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...
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...
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...
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...
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...
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...
you are here 4 425storing things locallyfunction shellGame() { localStorage.setItem("shell1", "pea"); localStorage.setItem("shell2", "empty"); localStorage.setItem("shell3", "empty"); localStorage["shell1"] = "...;
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...
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...
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...
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 ...
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...
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...
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...
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 ...
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...
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...
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...
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 ...
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, ...
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...
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...
you are here 4 441storing things locallyfunction init() { // button code here... var stickiesarray = localStorage["stickiesarray"]; if (!stickiesarray) { stickiesarray = []; localStorage.setItem("stickiesarray", (stickiesarray)); } els...
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...
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 ...
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...
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 ...
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 ...
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...
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...
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...
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);...
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...
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...
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...
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 =...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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 ______...
466 Chapter 9exercise solutionsfunction shellGame() { localStorage.setItem("shell1", "pea"); localStorage.setItem("shell2", "empty"); localStorage.setItem("shell3", "empty"); localStorage["shell1"] = "empty&qu...;
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...
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,...
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...
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...
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 ...
actionURI(https://freepdf-books.com /):www.freepdf-books.com actionURI(https://freepdf-books.com /):https://freepdf-books.com
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 ...
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...
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 ...
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...
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...
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...
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...
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 ...
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 ...
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...
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...
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...
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...
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...
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...
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() { ...
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...
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> ...
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 " ...
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....
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...
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...
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...
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...
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...
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!...
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...
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...
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...
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...
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...
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...
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...
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...
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 - ...
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...
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...
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’...
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...
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 ...
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...
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...
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...
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...
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 + ...
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...
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...
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...
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...
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 + ": "...;
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...
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...
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...
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); ...
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...
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...
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...
actionURI(https://freepdf-books.com /):www.freepdf-books.com actionURI(https://freepdf-books.com /):https://freepdf-books.com
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...
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...
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. ...
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...
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...
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...
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...
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 ...
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...
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...
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...
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...
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...
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...
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...
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...;
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...
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...
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...
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 ...
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...
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...
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...
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...
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...
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,...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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 (...
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...
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...
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...
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...
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...
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&...
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...