415 Head First HTML5 Programming

Gratis

0
0
610
3 months ago
Preview
Full text

Advance Praise for Head First HTML5 Programming

  (I’d put maybe10 books in this category, at the outside.)” and founder of the Hillside Group “I feel like a thousand pounds of books have just been lifted off of my head.”— Ward Cunningham, inventor of the Wiki and author of Down and Out in the Magic Kingdom and Someone Comes to Town, Someone Leaves Town “Head First HTML with CSS & XHTML teaches you how to do things right from the beginning without making the whole process seem overwhelming. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark While every precaution has been taken in the preparation of this book, the publisher and the authors assume no claim, the designations have been printed in caps or initial caps.

Table of Contents (the real thing)

  Thestory 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 Webvilleto get sense for 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 in3.8 pages (flat). and, adding a catch all50 How and where to add JavaScript to your pages53 How JavaScript interacts with your page54 How to bake your very own DOM55 A first taste of the DOM56 HTML5 is From Mars, JavaScript is from Venus58 You can’t mess with the DOM until the page has fully loaded.64 So, what else is a DOM good for anyway?66 Can we talk about JavaScript again?

Geolocation Wherever you go, there you are

  In this chapter we’re going to showyou how to create web pages that are location aware—sometimes you’ll be able to 5pin point your users down to the corner they’re standing on, and sometimes you’ll only be able to determine the area of town they’re in (but you’ll still know the town!). 219 How to make a request from JavaScript 220 Move over XML, meet JSON 226Writing an onload handler function 229 Displaying the gumball sales data 230 How to set up your own Web Server 231 Reworking our code to make use of JSON 236Moving to the Live Server 237 It’s a cliffhanger!

The Canvas HTML’s been liberated from being just a “markup” language

  450 How to get the sticky to delete from the event 451 Delete the sticky from the DOM, too 452Update the user interface so we can specify a color 453 JSON.stringify, it’s not just for Arrays 454 Using the new stickyObj 455 Don’t Try This at Home (or Blowing Up Your 5 Megabytes) 458Now that you know localStorage, how are you going to use it? 509 Getting the workers started 510 Implementing the worker 511 Back to the code: how to process the worker’s results 514Fitting the canvas to the browser window 517 The anal-retentive chef coder 518 In the Laboratory 520 Bullet Points524 Exercise Solutions 526 table of contents#1 Modernizr 532 #2 Audio533 #3 jQuery534 #4 XHTML is dead, long live XHTML 536 #5 SVG#7 Web sockets 539 537 #6 Offline web apps 538 #8 More canvas API 540 #9 Selectors API 542#10 But, there’s even more!

And we know what your brain is thinking

  For example, studies show that putting words within the pictures they describe (as opposed tosomewhere else in the page, like a caption or in the body text) causes your brain to try to makes sense of how the words and picture relate, and this causes more neurons to fire. And when text and pictures workimg a em a together, we embedded the text in the pictures because your brain works more effectivelywhen the text is within the thing the text refers to, as opposed to in a caption or buried in the text somewhere.

BE the Browser little humor, surprise, or interest

Puzzles

  We include content for both sides of your brain, because the more of your brain you engage, the more likely you are to learn and remember, and the longer you can stayfocused. For some of them, there is no right answer, and for others, part of the learning experience of the Brain Power activities is for you to decide if and when your answers are right.

Software requirements

  It’s also worth your time to learn how to use the browser developer tools; each of the major browsers has built-in tools you can useto inspect the JavaScript console (you can see errors as well as output you display using , a handy alternative to ), web storage usage, the DOM, CSS console.log alert style that’s been applied to elements, and much much more. the introAcknowledgmentsEven more technical review: This is becoming a recurring theme in our books, but we wanted to Note to Editor: can we see give another shout out to David Powers, our esteemed technical if we can lock this guy in reviewer, and author of many books including PHP Solutions: for our next three books?

Safari® Books Online

  Now we’ve got a language tuned forreceived a “Dearbuilding true web applications with local storage, 2D drawing, John” letter in 2009 and we’ll be visitingoffline support, sockets and threads, and more. The story of XHTML later in the “Where are they now”HTML wasn’t always pretty, and it’s full of drama (we’ll get to all segment.that), but in this chapter, we’re first going to go on a quick joyride through Webville to get sense for 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).

HTML5-o-Matic

  getting to know HTML5After taking a careful look at the HTML on the page 2, can you see any markup that the might change with HTML5? Step 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 newHTML5 shine.

STEP 1

  Here’s the amazing part: the newthe crew thatdoctype for HTML5 is simply:got the 4.01 doctype tattoo <!doctype html> to remember it. Not onlythat, it will work in your older browsers too.e The W3C HTML Standards guys haveally mean it this time.promised us they r If you’re a fan of the Extreme Makeovers or The Biggest Loser television shows, you’re going to love Step 2.

STEP 2 <meta http-equiv="content-type" content="text/html; charset=UTF-8">

  When you specify the meta tag in HTML5, just supply the tag along with a characterencoding. Believe it or not, all browsers (old and new) already understand this just works.meta description, so you can use it on any page and it getting to know HTML5And now for Step 3, the step that brings it all home.

STEP 3

  <link type="text/css" rel="stylesheet" href="lounge.css">Old skool To upgrade this for HTML5, we just need to remove the type attribute. So,after we remove the type attribute, the new link looks like this: <link rel="stylesheet" href="lounge.css">HTML5 And, because you acted fast, we’ve got a special bonus for you.

Bonus

  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 everythingin it is still supported in HTML5) and all you need to do is know how to specify your and the rest of the doctype tags in the element to get started with HTML5.<head> But, you’re right, we were being silly, of course there is more to HTML5 than just updating a few elements. Yes, it does seem a little magical that after years of using complex doctypes we can now just simplify it to “we’re using HTML.”Here’s what happened: HTML used to be based on a standard called SGML, and that standard required both the complex formof the doctype and the DTD.

Behind

  APIs, otherwise known as Application Programming The APIs give you access to audio, Interfaces, expose a set of 4 video, 2D drawing with the canvas, objects, methods, and properties local storage and a bunch of other that we can use to access all great technologies needed to build the functionality of these apps. And don’t worry, we know this is your first time meeting the HTML5 family members, so the answers are at the end of the chapter.

ISSION: YOUR FIRST M NNaISSaNCE ELOW CH BROWSER B BROWSER RECO

  IS TExT THINGS:PPORT FOR Ea ETERMINE *TH UP WITH SUCH LEvEL OF SU EDaCT GO OUT aND D S THaT kEEP R/ THE CURRENT ORT. WPORTED, aND IF IT IS SUP H IT SUPPORT ************ a CHECkMaRk GNMENT!

ISSION: YOUR FIRST M NNaISSaNCE BROWSER RECO

SOLUTION

  But the good news is that all browsers are moving towards the HTML5 standard and relatedtechnologies (even the mobile browsers) and so over time graceful degradation will be more the exceptionthan the rule (although you’ll always want to do what you can to give your users a meaningful experience nomatter what browser they’re on). The W3C is the standards body that formally recommends the While there is plenty of healthy competition in the marketplace A:A: HTML5 standard, and what you need to know about the W3C is that for browsers (desktop and mobile), in reality many of these browsers they are a conservative bunch, so conservative that they’d prefer are based on a few common HTML engines.

HTML Archaeology

  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 goodunderstanding of using markup languages and stylesheets to create great looking web pages. 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 takeyou through everything you need to know to write the applications in this book.

Writing Serious JavaScript Revisited..

  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 (cans > 0) { This is a while loop. Reduce the number of cans left by 1} document.write(lyrics); We’ve stored all the lines to the song in the variable lyrics, so now we tellthe web page to write it, which just means the string is added to thepage so you can see the song.

A Test Drive

  There’s no technical difference between the song lyrics directly into the body element (and that the two; in other words, there’s nothing special you dowould have taken a lot of typing), or we can have code to turn a page written with HTML, JavaScript and/or do all the hard work for us (which we did), and then CSS into a web application. When we have a page that is acting more like an Keep in mind we’re just getting our feet wet here; we’re application than just a static document, then we startgoing to spend a lot more time in this book seeing how thinking of it as a web application and less as a web we can take a page and dynamically fill in its content page.

HTML5 Markup + JavaScript APIs + CSS = Crazy Delicious

  That is, we have markup to build the core structure of our pages, we haveJavaScript along with all its APIs to add behavior and new functionality, and we have CSS to style ourpages—and together, these are the technologies we’re all going to use to build tomorrow’s web apps. So, we say HTML5 is markup 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 w3.org for more information.

Congratulations, you’ve finished Chapter 1 and

  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 is HTML5?”Careful now, there are some distractions thrown in with that pile of magnets.

Canvas

  Making changes to the doctype and <meta> tag won’t break your pages in older browsers.ƒ UTF-8 is now the standard charset in use on the Web.ƒ The <meta> tag used for specifying the character set has been simplified to includeonly the character encoding.ƒ The type attribute is no longer needed in the <script> tag or in a stylesheet link to CSS. Developers and the W3C decided tokeep extending and improving HTML instead.ƒ ƒ ƒCSS is the style standard for HTML5; many people include CSS when they usethe term “HTML5” to describe the family of technologies used to create web applications.

Down 2. __________ plug could also be called spam

  dog = “good” + dog;var dog = “fido”;javascript and the dom Finally, we have a variable and we have a value (a literal 3 value, like 10, or the result of evaluating an expression(like )), and all we need to do is totalScoops / peopleSyntax Fun assign the value to the variable:ƒ Each statement ends in a semicolon. We’ll beRule#1: Start your variables with a letter,talking about objects soon enough, an underscore or a dollar sign.but for now you can think of an object as a collection of things, whereas a You want to get off to a good start with naming primitive is just one thing that can’t your variables, not just by making them meaningful, be broken up into anything else.but also by using a letter (small or uppercase), an underscore character or a dollar sign.

Webville Guide to Better Naming

  When you add HTML fileYou can type JavaScript in the element, it is <head>your code executed as soon as the browser parses <head>right into the head (which it does first!), before it has your web page, <script> parsed the rest of the page.statementor reference </script>a separate JavaScript file Add your script by referencing <script src=”mycode.js”>using the src a separate JavaScript file. Put the URL of the file in the attribute of the srcOr you can <body> opening tag and make sure <script>place your code you close the script element with (or a reference . If you’re linking to a file in </script><script>to your code) the same directory, you can just use the statement in the body.

Or, how two totally different technologies hooked up

  There are a few ways tomake this happen, but for now lets concentrate on one— it’s a little wormhole of sorts that allows JavaScript to getaccess to any element, and it’s called getElementById. javascript and the domHere’s a simple DOM; it’s got a few HTML paragraphs, each with Let’s start with a DOM.an identifying it as the green, red or blue planet.

Once getElementById gives you an element, you’re ready do something with it

  In our case, the JavaScript is executing when the browser firstloads the head of the page, and before the rest of the page has loaded, and so the DOM hasn’t been fully created yet. 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 nowlet’s just take a quick look so you’ve got it in the back of your mind: Look up and Get elements from the DOM.retrieve one or Of course you already know this because more elements we’ve been using document.getElementById, form from the DOM.

Remove elements from the DOM

  Remove You can also remove elements from the existing ul DOM by taking a parent element and elements.removing any of its children. Again, you’ll see the element removed in your li li browser window as soon as it is deleted from the DOM.

Get and set the attributes of elements

  Know the size of your array, or else You can easily get the size of your array by referring to a property of the array called length: We’ll talk more about properties in thevar numItems = tempByHour.length;next chapter; for now, just know that every array has this length property thattells you the number of items in the array. We’ve given you most of the code; it’s your job to finish it up so thatit sets the content of each list item to the corresponding temperature from the array (e.g., the list item with id = “temp0” will get the temperature at index 0 in the array, and so on).

A: You could set the value of the array at the

  point number, like 3.2, so we use Math.floor kind of object that’s built into JavaScript.index to null; for example, myArray[2] = null.to make sure we get an integer number that It’s special because you can use numerical But that would mean the length of the Array we can use as an index into the array toindexes to access the values stored in the stays the same. All Math.floor does is array, something you can’t do with otheritem altogether (using the function splice).drop the numbers after the decimal point in (non-array) objects, or objects that you In that case, the indexes of the items that a floating point number.

Q: Q:

  ƒAssign a function to the window.onload property to run the code in that function afterthe browser has finished loading the web page. When the browser loads a web page, it creates a Document Object Model (DOM),which is an internal representation of the web page.

HTML5Cross

  5 < 10 is a _________ expression. 18 17 16 15 14 13 11 2 Time to work a different part of your brain with a crossword.

Across 2. 5 < 10 is a _________ expression

  javascript and the dom You’ve seen the different types of far about JavaScript variables, Based on what you know so expressions you can use in JavaScript,expressions and statements, see now it’s time to put that knowledge to workif you can figure out which of by evaluating some expressions yourself. PI gives you the value of pi (you know, 3.14....)z = z + 1; z--;illegal!z y; x = z * t; while (highNoon) { z--; Not this kind of expression!} exercise solutions 10 15 5 var count = 0; for (var i = 0; i < 5; i++) { count = count + i; } alert("count is " + count); for (var berries = 5; berries > 0; berries--) { alert("Eating a berry"); }Snippet 1 Snippet 3 Snippet 2What count does the alert show?

Snippet 4

  The problem is that some of Code Magnets Solutionvar word1 = "a"; var word2 = "nam"; var word3 = "nal p"; var word4 = "lan a c"; var word5 = "a man a p"; A palindrome is a sentence that canvar phrase = "";be read the same way backwards and forwards! i == 4 word2 i < 3 word4 + word0 i-- else i = 0 i = 3 word3 javascript and the dom<!doctype html> <html lang="en"> BE the Browser <head> Solution <title>Movies</title> Your job is the act like </head> you’re the browser.

Here’s our DOM

  </ul> </body> </html> javascript and the dom Below you’ll find a web page with a list of empty items ready for yourJavaScript to fill in with temperatures. We gave you most of the code; it was your job to finish it up so that it set the content of each list itemto the corresponding temperature from the array.

M AcrossDown

  introducing webville tunesGet ready for Webville Tunes Okay, we’ve dragged you through a lot of JavaScript fundamentals so far in this book, and while we’ve talked a good game on buildingweb apps, we don’t have a lot to show for it, yet. </html>Give it a test drive Go ahead and type in the code above, load it into your favorite browser and give it a spin before moving on to the next page.

We need two things:

  Now, you’re not required to handle any of theseevents, but you’ll need to handle them if you want interesting things to happen when they occur—like, say, when the button click eventhappens, you might want to add a new song to the playlist; when new data arrives you might want to process it and display it on yourpage; when a timer fires you might want to tell the user their hold on front row tickets is going to expire, and so on. We’ll use its id,form ul id=”playlist” “songTextInput”, to get it.input id=”songTextInput” input id=”addButton” value=”Blue Suede Strings, by Elvis Pagely” Then we can use the value property of the input element to get the text the user typed intoUsing the getElementById method, we the input field.can get a handle to the songTextInput input element in the form.

Here’s what we need to do:

  1 You might have noticed that we alreadyput an empty list in the HTML markupbody (an empty <ul> element to be exact) backHere’s the list inwhen we first typed it in. Notice the order inwhich the songs are added to the page, and make sure the elements are in the right places in the DOM too.

Draw the rest of the DOM here for the playlist above

  Here’s how we do that: <ul> , we tell the element in the tree (we gave it an id of “playlist” to make that easy) andthen to add the To add a new element to the DOM you have to know where you want to put it. To add the song to the playlist, you then created 3li a <li> element using document.createElement, and set the content of the element to the song name Blue Suede Strings, using innerHTML.by Elvis Pagely You create a new <li> element and set the content of the <li>element to the song name.body Finally, you added the new <li> element to the DOM 4 by adding it as a child of the parent <ul> element.

Ready Bake Code

  element in playlist.html :Now you just need to add two lines to your code, in playlist.js , that will load and save the playlist: And this saves your song each time you add one to the playlist. 2) Set up a button click event and written the code to capture and handle the button click.3) Asked the DOM for information.4) Created and added new elements to the DOM.

Down Across

  The default value of a form input element if the user doesn’t doesn’t type anything is the ______ string.type anything is the ______ string. Notice theorder in which the songs are added to the page, and make sure the elements are in the right places in theDOM too.

HTML5cross Solution

1 H A 2 C R E A T E E L E M E N T H D 3 4 I A P P E N D C H I L D L L E 5 6 D E V E N T T R E E I 7 8 S D O C U M E N T 9 E M P T Y B V A J E G E N E C 10 T L O C A L S T O R A G E Y SAcross

Down 2. DOM’s method for creating new elements

  I was thinking of " + answers[index]; } else { answer = "Sorry, I was thinking of " + answers[index]; } alert(answer); </script> Expanding your vocabulary You can already do a lot with JavaScript, let’s take a look at some of the things you know how to do: Grab an element from the document object model. So far, though, a lot of your knowledge is informal—sure, you can get an element out of the DOM and assign some new HTML to it, but if we askedyou to explain exactly what document.getElementById is technically, well, that might be a little more challenging.

Dokumen baru