You are previewing Head First HTML5 Programming.

Head First HTML5 Programming

Cover of Head First HTML5 Programming by Elisabeth Robson... Published by O'Reilly Media, Inc.
  1. Head First HTML5 Programming building web apps with javascript
  2. Dedication
  3. A Note Regarding Supplemental Files
  4. Advance Praise for Head First HTML5 Programming
  5. Praise for other books from Eric Freeman & Elisabeth Robson
  6. Authors of Head First HTML5 Programming
  7. How to Use this Book: Intro
    1. Who is this book for?
      1. Who should probably back away from this book?
    2. We know what you’re thinking
    3. And we know what your brain is thinking
    4. Metacognition: thinking about thinking
    5. Here’s what WE did:
    6. Here’s what YOU can do to bend your brain into submission
    7. Read me
    8. Software requirements
    9. The technical review team
    10. Acknowledgments
    11. Even more Acknowledgments!
    12. Safari® Books Online
  8. 1. Getting to Know HTML5: Welcome to Webville
    1. Would the REAL HTML5 please stand up...
    2. How HTML5 really works...
    3. What can you do with JavaScript?
    4. Writing Serious JavaScript
    5. Writing Serious JavaScript Revisited...
  9. 2. Introducing JavaScript and the DOM: A Little Code
    1. The Way JavaScript Works
    2. What can you do with JavaScript?
    3. Declaring a variable
      1. Three steps of creating a variable
    4. How to name your variables
      1. Rule#1: Start your variables with a letter, an underscore or a dollar sign
      2. Rule #2: Then you can use any number of letters, numeric digits, underscores or dollar signs
      3. Rule #3: Make sure you avoid all of JavaScript’s reserved words
    5. Getting Expressive
    6. Doing things over and over...
    7. Make decisions with JavaScript
    8. Making more decisions... and, adding a catchall
    9. How and where to add JavaScript to your pages
    10. How JavaScript interacts with your page
    11. How to bake your very own DOM
    12. A first taste of the DOM
    13. Test drive the planets
    14. You can’t mess with the DOM until the page has fully loaded
      1. Reload the page
    15. So, what else is a DOM good for anyway?
    16. Can we talk about JavaScript again? Or, how to store multiple values in JavaScript
      1. How to create an array
      2. Adding another item to the array
      3. Using your array items
      4. Know the size of your array, or else
    17. The Phrase-O-Matic
  10. 3. Events, Handlers and All that Jazz: A Little Interaction
    1. Get ready for Webville Tunes
    2. Getting started...
      1. Give it a test drive
    3. But nothing happens when I click “Add Song”
    4. Handling Events
    5. Making a Plan...
    6. Getting access to the “Add Song” button
    7. Giving the button a click handler
      1. Putting it to a test...
    8. A closer look at what just happened...
    9. Getting the song name
    10. How do we add a song to the page?
    11. How to create a new element
    12. Adding an element to the DOM
    13. Put it all together...
    14. ...and take it for a test drive
    15. Review—what we just did
    16. How to add the Ready Bake Code...
    17. Integrating your Ready Bake Code
      1. Test drive the saved songs
  11. 4. JavaScript Functions and Objects: Serious JavaScript
    1. Expanding your vocabulary
    2. How to add your own functions
      1. Create a checkGuess function
    3. How a function works
    4. Local and Global Variables
      1. Know the difference or risk humiliation
    5. Knowing the scope of your local and global variables
    6. The short lives of variables
    7. Oh, did we mention functions are also values?
    8. What you can do with functions as values
    9. Did someone say “Objects”?!
    10. Thinking about properties...
    11. How to create an object in JavaScript
    12. Some things you can do with objects
    13. Let’s talk about passing objects to functions
      1. Putting Fido on a diet....
    14. Our next showing is at....
    15. Testing at the drive-in
    16. Objects can have behavior too...
    17. Meanwhile back at Webville Cinema...
    18. But we know that can’t be quite right...
    19. Let’s get the movie parameter out of there...
    20. Now what?
    21. Adding the “this” keyword
    22. A test drive with “this”
    23. How to create a constructor
    24. Now let’s use our constructor
    25. How does this really work?
    26. Test drive your constructor right off the factory floor
    27. What is the window object anyway?
    28. A closer look at window.onload
    29. Another look at the document object
    30. A closer look at document.getElementById
    31. One more object to think about: your element objects
  12. 5. Making Your HTML Location Aware: Geolocation
    1. Location, Location, Location
    2. The Lat and Long of it...
    3. How the Geolocation API determines your location
    4. Just where are you anyway?
    5. Test drive your location
    6. What we just did...
    7. How it all fits together
    8. Revealing our secret location...
    9. Writing the code to find the distance
    10. Location-enabled test drive
    11. Mapping your position
    12. How to add a Map to your Page
      1. Getting ready to create a map...
    13. Displaying the Map
    14. Test drive your new heads-up display
    15. Sticking a Pin in it...
    16. Testing the marker
    17. Meanwhile back at the Geolocation API...
    18. Can we talk about your accuracy?
    19. Accuracy Test
    20. “Wherever you go, there you are”
      1. How we’re going to track your movements
    21. Getting the app started
    22. Reworking our old code...
      1. Writing the watchLocation handler
      2. Writing the clearWatch handler
      3. We still need to make a small update to displayLocation...
    23. Time to get moving!
    24. You’ve got some Options...
      1. Can we talk about your accuracy, again?
    25. The world of timeouts and maximum age...
    26. How to specify options
    27. Let’s finish this app!
    28. Integrating our new function
    29. And one more time...
  13. 6. Talking to The Web: Extroverted Apps
    1. Mighty Gumball wants a Web app
    2. A little more background on Mighty Gumball
    3. Just a quick start...
      1. Turn the engine over...
    4. So how do we make requests to web services?
    5. How to make a request from JavaScript
    6. Move over XML, meet JSON
    7. A quick example using JSON
    8. Let’s get to work!
      1. Writing an onload handler function
    9. Displaying the gumball sales data
    10. Watch Out, Detour Ahead!
    11. How to set up your own Web Server
    12. How to set up your own Web Server, continued
    13. Back to the code
    14. Let’s test this already!
    15. Impressing the client...
    16. Reworking our code to make use of JSON
    17. The Home Stretch...
    18. Moving to the Live Server
    19. A Live Test Drive...
    20. It’s a cliffhanger!
    21. Remember, we left you with a cliffhanger? A bug
    22. So, what do we do now?!
    23. What Browser Security Policy?
      1. Acceptable Behavior for JavaScript code
      2. Unacceptable Behavior for JavaScript code
    24. So, what are our options?
    25. Meet JSONP
    26. But what is the “P” in JSONP for?
    27. Let’s update the Mighty Gumball web app
    28. Test drive your new JSONP-charged code
    29. Improving Mighty Gumball
    30. Step 1: Taking care of the script element...
    31. Step 2: Now it’s time for the timer
    32. A time-driven test drive
    33. Step 3: Reimplementing JSONP
      1. First, let’s set up the JSONP URL
      2. Next, let’s create a new script element
      3. How do we insert the script into the DOM?
      4. Now let’s write the code to insert the script into the DOM
    34. We almost forgot: watch out for the dreaded browser cache
    35. One more TIME test drive
    36. How to remove duplicate sales reports
    37. Updating the JSON URL to include the lastreporttime
    38. Test drive lastReportTime
    39. A Special Message from Chapter 7...
  14. 7. Bringing Out Your Inner Artist: The Canvas
    1. Our new start-up: TweetShirt
    2. Checking out the “comps”
    3. Let’s drop in on the TweetShirt crew...
    4. How to get a canvas into your web page
    5. Test drive your new canvas
    6. How to see your canvas
    7. Drawing on the Canvas
    8. A little Canvas test drive...
    9. A closer look at the code
    10. Failing gracefully
    11. TweetShirt: the Big Picture
    12. First, let’s get the HTML in place
    13. Now, let’s add the <form>
    14. Time to get computational, with JavaScript
    15. Writing the drawSquare function
    16. Time for a test drive!
      1. Why are we seeing the old squares and the new squares when we preview?
    17. Add the call to fillBackgroundColor
      1. Another quick test drive to make sure our new fillBackgroundColor function works...
    18. Meanwhile, back at
      1. And, a couple of hours later...
    19. Drawing with Geeks
    20. Breaking down the arc method
    21. A little taste of using the arc
    22. I say degree, you say radian
    23. Back to writing the TweetShirt circle code
    24. Writing the drawCircle function...
      1. ...and test drive!
    25. Welcome back...
    26. Getting your tweets
    27. Test driving Tweets
    28. Giving drawText a spin
    29. Completing the drawText function
    30. A quick test drive and then LAUNCH!
    31. Yet another test drive
      1. So you have a path! Now what?
  15. 8. Not Your Father’s TV: Video ...With Special Guest Star “Canvas”
    1. Meet Webville TV
    2. The HTML, let’s get it done...
    3. Plug that set in and test it out...
    4. How does the video element work?
    5. Closely inspecting the video attributes...
    6. What you need to know about video formats
    7. The contenders
    8. How to juggle all those formats...
    9. How to be even more specific with your video formats
    10. I was told there would be APIs?
    11. A little content “programming” on Webville TV
    12. Implementing Webville TV’s playlist
    13. So what’s up with that event handler code?
    14. How to write the “end of video” handler
    15. Another test drive...
    16. How the canPlayType method works
      1. Putting canPlayType to use
      2. Integrating the getFormatExtension function
      3. And test drive...
    17. We need your help!
    18. Step inside the booth, let’s take a look...
    19. Unpacking the Demo Unit
    20. Inspecting the rest of the factory code
      1. And now the JavaScript...
      2. Looking at the button handlers
    21. The setEffect and setVideo handlers
    22. And here are the helper functions
    23. That new demo machine smell...test drive time!
    24. Getting our demo videos ready...
    25. Implementing the video controls
    26. Implementing the rest of the video controls
    27. Another test drive!
    28. Taking care of a loose end...
    29. And another...
    30. Switching test videos
      1. Switch drivers and test drive!
    31. It’s time for special effects
    32. The FX plan
    33. Time to get those effects buttons working
    34. How video processing works
    35. How to process video using a scratch buffer
    36. Implementing a scratch buffer with Canvas
    37. How to position the video and canvases
    38. Writing the code to process the video
    39. How to create the buffer
    40. How to process the buffer
      1. We’ve processed one frame, what next?
    41. Now we need to write some effects
    42. A film noir test drive
    43. The Big Test Drive
    44. If only it were a perfect world...
    45. How to use error events
    46. Test Crash!
    47. Where can you go from here?
  16. 9. Storing Things Locally: Web Storage
    1. How browser storage works (1995 - 2010)
    2. How HTML5 Web Storage works
    3. Note to self...
    4. Time for a test drive!
    5. Were Local Storage and the Array separated at birth?
      1. But wait, there’s more!
    6. Getting serious about stickies
    7. Creating the interface
    8. Now let’s add the JavaScript
    9. Time for another test drive!
    10. Completing the user interface
    11. Yet another test drive!
    12. We need to stop for a little scheduled service
    13. Do-It-Yourself maintenance
    14. We have the technology...
    15. Reworking our app to use an array
      1. Before...
      2. New and improved
    16. Converting createSticky to use an array
    17. What needs to change?
    18. Putting it all together
    19. Putting it all together continued...
    20. Test Drive!
    21. Deleting sticky notes
    22. The deleteSticky function
    23. How do you select a sticky to delete?
    24. How to get the sticky to delete from the event
    25. Delete the sticky from the DOM, too
      1. Okay, test it...
    26. But of course we can!
    27. Update the user interface so we can specify a color
    28. JSON.stringify, it’s not just for Arrays
    29. Using the new stickyObj
    30. Test drive sticky note colors
    31. Now that you know localStorage, how are you going to use it?
  17. 10. Putting JavaScript to Work: Web Workers
    1. The Dreaded Slow Script
    2. How JavaScript spends its time
    3. When single-threaded goes BAD
    4. Adding another thread of control to help
    5. How Web Workers work
    6. Your first Web Worker...
      1. How to create a Web Worker
    7. Writing Manager.js
    8. Receiving messages from the worker
    9. Now let’s write the worker
      1. Writing the worker’s message handler
    10. Serving up a test drive
    11. Virtual Land Grab
    12. Take a look around
    13. How to compute a Mandelbrot Set
    14. How to use multiple workers
    15. Let’s build the Fractal Explorer app
      1. Creating the Fractal Viewer HTML Markup
    16. Creating workers, and giving them tasks...
    17. Writing the code
    18. Getting the workers started
    19. Implementing the worker
    20. A little pit stop...
    21. Time to get back on the road...
    22. Back to the code: how to process the worker’s results
    23. Psychedelic test drive
      1. Handling a click event
    24. Another test drive
    25. Fitting the canvas to the browser window
    26. The anal-retentive chef coder
    27. Time for the final test drive!
    28. Congratulations! You made it to the end
  18. A. Leftovers: The Top Ten Topics (We Didn’t Cover)
    1. #1 Modernizr
      1. Including Modernizr in your page
      2. How to detect support
    2. #2 Audio
      1. A Standard for Audio Encodings
    3. #3 jQuery
    4. #4 XHTML is dead, long live XHTML
    5. #5 SVG
    6. #6 Offline web apps
    7. #7 Web Sockets
    8. #8 More canvas API
    9. #9 Selectors API
    10. #10 But, there’s even more!
      1. Indexed Database API and Web SQL
      2. Drag and Drop
      3. Cross-document Messaging
      4. And we could go on...
    11. The HTML5 Guide to New Construction
    12. Adding style to your new construction with CSS3
  19. B. This isn’t goodbye
  20. Index
  21. About the Authors
  22. Colophon
  23. Copyright

Chapter 1. Getting to Know HTML5: Welcome to Webville

image with no caption

HTML has been on a wild ride. Sure, HTML started as a mere markup language, but more recently HTML’s put on some major muscle. Now we’ve got a language tuned for building true web applications with local storage, 2D drawing, offline support, sockets and threads, and more. The story of HTML wasn’t always pretty, and it’s full of drama (we’ll get to all that), but in this chapter, we’re first going to go on a quick joyride through Webville to get a sense of everything that goes into “HTML5.” Come on, hop in, we’re headed to Webville, and we’re going to start by going from zero to HTML5 in 3.8 pages (flat).


Heads up: XHTML received a “Dear John” letter in 2009 and we’ll be visiting XHTML later in the “Where are they now” segment.


image with no caption

Congratulations, 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!

image with no caption

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. And as you can see, if you’re familiar with HTML 4.01, then you’re in great shape because HTML5 is a superset of HTML 4.01 (meaning practically everything in it is still supported in HTML5) and all you need to do is know how to specify your doctype and the rest of the tags in the <head> element to get started with HTML5.

But, you’re right, we were being silly, of course there is more to HTML5 than just updating a few elements. In fact, what everyone is excited about is the ability to build rich, interactive pages (or even sophisticated web applications), and to support that, HTML5 provides a whole family of technologies that works hand in hand with the HTML5 markup language.

But hang on; before we get there we’ve got just a bit more work to do to make sure we’re ready with our markup.


We 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 markup and adding style, and so on.

If you aren’t familiar with all these, we’re going to make a small suggestion (and a shameless plug): there’s another book that precedes this one, Head First HTML with CSS & XHTML, and you should read it. And if you’re somewhat familar with markup languages, you might want to skim it or use it as a reference while reading this book.

We’ve also put a small guide to HTML5 markup & CSS3 in the appendix. If you just want a quick overview of the new additions, have a quick read over them at the end of the book.

image with no caption

Would the REAL HTML5 please stand up...

Okay, you’ve patiently humored us by sitting through our “HTML5-o-Matic” skit, and we’re sure you’ve already guessed there’s a lot more to HTML5 than that. The word on the street is that HTML5 removes the need for plug-ins, can be used for everything from simple pages to Quake-style games and is a whipped topping for desserts. HTML5 seems to be something different to everyone...

image with no caption
image with no caption
image with no caption
image with no caption
image with no caption
image with no caption
image with no caption

The good news is, HTML5 is all these things. When people talk about HTML5 they mean a family of technologies that, when combined, gives you a whole new palette for building web pages and applications.

How 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 CSS3 that give you even more power to style your pages. And then there’s the turbo charger: JavaScript, and a whole new set of JavaScript APIs that are available to you.


You’ll find a nice Webville guide to the new HTML5 markup & CSS3 properties in the appendix.

Let’s take a look behind the scenes and see how this all fits together:

image with no caption
image with no caption

Behind the Scenes

image with no caption


...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...

image with no caption
image with no caption

Even though it will be a while before the standard gets signed, sealed and delivered, you’ll be using browsers that fully support HTML5 long before then. In fact, on modern browsers many features are already supported across the board. That’s why it’s a great idea to get started using HTML5 now. Plus if you start now, you’ll be able to impress your friends and coworkers with all your cutting edge knowledge.


And get that raise sooner!

image with no caption

Hold on, take a deep breath.

First of all HTML5 is a superset of HTML, and so your goal should be to write only one HTML page. You’re right in that the features supported by any one browser may differ, depending on how current the browser is, and how aggressive your users are in upgrading. So, we need to keep in mind that some of the newer features of HTML5 might not be supported, which leads back to your question of how to handle that.

Now, one of the design principles behind HTML5 is to allow your pages to degrade gracefully—that means if your user’s browser doesn’t provide a new feature, then you should provide a meaningful alternative. In this book we’re going to show you how to write your pages to do that.

But the good news is that all browsers are moving towards the HTML5 standard and related technologies (even the mobile browsers) and so over time graceful degradation will be more the exception than the rule (although you’ll always want to do what you can to give your users a meaningful experience no matter what browser they’re on).

image with no caption

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 repurposing it as firewood) we know you probably have a good understanding of using markup languages and stylesheets to create great looking web pages. Knowing those two technologies can get you a long way...

But, with HTML5 things are changing: web pages are becoming rich experiences (and full blown applications) that have behavior, are updated on the fly, and interact with the user. Building these kinds of pages requires a fair bit of programming and if you’re going to write code for the browser, there’s only one game in town: JavaScript.

Now, if you’ve programmed or written simple scripts before, you’re going to be in good shape: JavaScript (despite some rumors) is a fantastic language and we’ll take you through everything you need to know to write the applications in this book. If you haven’t programmed before, we’re going to do everything we can to take you along for the ride. In either case, one of the huge benefits of JavaScript is how accessible it is to new programmers.


We can’t think of a better or more fun way to learn to program!

So, what now? Let’s just briefly get introduced to a little JavaScript and then we’ll really dive in deep in Chapter 2. In fact, for now, don’t worry too much about getting every detail over the next few pages—we just want you to get a feel for JavaScript.

What 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...

image with no caption

Writing 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 at you. For now, get started by going through the code to get a feel for it. Write down what you think each line does. Don’t worry, we don’t expect you to understand everything yet, but we bet you can make some really good guesses about what this code does. And, when you’re done, turn the page and see how close you were...

image with no caption
image with no caption

Writing Serious JavaScript Revisited...

Walk through the code again and see if you were on the mark. At this point you just want to get a feel for the code; we’ll be stepping through everything in detail soon enough.

image with no caption
image with no caption
image with no caption

We’ll give you our unofficial answer:

image with no caption

You see, when most people are talking about the promise of HTML5, what they mean is all of these technologies combined. That is, we have markup to build the core structure of our pages, we have JavaScript along with all its APIs to add behavior and new functionality, and we have CSS to style our pages—and together, these are the technologies we’re all going to use to build tomorrow’s web apps.

Now, why did we say unofficial? Well, there are people who like to make hard distinctions among these technologies and which standard each belongs to. And that is fine and has its place. But, what we care about is this: what technologies are available in the browser, and are they ready for us to use to craft our pages and applications? So, we say HTML5 is markup + JavaScript APIs + CSS, and we think that is what people generally mean when talking about HTML5 as a technology.


If you’re really interested in how these technologies fit together as a set of standards (and we all should be) then we encourage you to visit for more information.

The best content for your career. Discover unlimited learning on demand for around $1/day.