Solutions to the Chapter Questions - Learning PHP, MySQL, JavaScript, CSS & HTML5 (2014)

Learning PHP, MySQL, JavaScript, CSS & HTML5 (2014)

Appendix A. Solutions to the Chapter Questions

Chapter 1 Answers

1. A web server (such as Apache), a server-side scripting language (PHP), a database (MySQL), and a client-side scripting language (JavaScript).

2. HyperText Markup Language: the web page itself, including text and markup tags.

3. Like nearly all database engines, MySQL accepts commands in Structured Query Language (SQL). SQL is the way that every user (including a PHP program) communicates with MySQL.

4. PHP runs on the server, whereas JavaScript runs on the client. PHP can communicate with the database to store and retrieve data, but it can’t alter the user’s web page quickly and dynamically. JavaScript has the opposite benefits and drawbacks.

5. Cascading Style Sheets: styling and layout rules applied to the elements in an HTML document.

6. Probably the most interesting new elements in HTML5 are <audio>, <video>, and <canvas>, although there are many others such as <article>, <summary>, <footer>, and more.

7. Some of these technologies are controlled by companies that accept bug reports and fix the errors like any software company. But open source software also depends on a community, so your bug report may be handled by any user who understands the code well enough. You may someday fix bugs in an open source tool yourself.

Chapter 2 Answers

1. WAMP stands for “Windows, Apache, MySQL, and PHP”; M in MAMP stands for Mac instead of Windows; and the L in LAMP stands for Linux. They all refer to a complete solution for hosting dynamic web pages.

2. Both 127.0.0.1 and http://localhost are ways of referring to the local computer. When a WAMP or MAMP is properly configured, you can type either into a browser’s address bar to call up the default page on the local server.

3. FTP stands for File Transfer Protocol. An FTP program is used to transfer files back and forth between a client and a server.

4. It is necessary to FTP files to a remote server in order to update it, which can substantially increase development time if this action is carried out many times in a session.

5. Dedicated program editors are smart and can highlight problems in your code before you even run it.

Chapter 3 Answers

1. The tag used to start PHP interpreting code is <?php ... ?>, which can be shortened to <? ... ?> but is not recommended practice.

2. You can use // for a single-line comment or /* ... */ to span multiple lines.

3. All PHP statements must end with a semicolon (;).

4. With the exception of constants, all PHP variables must begin with $.

5. Variables hold a value that can be a string, a number, or other data.

6. $variable = 1 is an assignment statement, whereas $variable == 1 is a comparison operator. Use $variable = 1 to set the value of $variable. Use $variable == 1 to find out later in the program whether $variable equals 1. If you mistakenly use $variable = 1where you meant to do a comparison, it will do two things you probably don’t want: set $variable to 1 and return a true value all the time, no matter what its previous value was.

7. A hyphen is reserved for the subtraction operators. A construct like $current-user would be harder to interpret if hyphens were also allowed in variable names and, in any case, would lead programs to be ambiguous.

8. Variable names are case-sensitive. So, for example,$This_Variable is not the same as $this_variable.

9. You cannot use spaces in variable names, as this would confuse the PHP parser. Instead, try using the _ (underscore).

10.To convert one variable type to another, reference it and PHP will automatically convert it for you.

11.There is no difference between ++$j and $j++ unless the value of $j is being tested, assigned to another variable, or passed as a parameter to a function. In such cases, ++$j increments $j before the test or other operation is performed, whereas $j++ performs the operation and then increments $j.

12.Generally, the operators && and and are interchangeable except where precedence is important, in which case && has a high precedence, while and has a low one.

13.You can use multiple lines within quotations marks or the <<<_END ... _END; construct to create a multiline echo or assignment. The closing tag must begin at the start of a line, and end with a semicolon followed by a new line.

14.You cannot redefine constants because, by definition, once defined they retain their value until the program terminates.

15.You can use \' or \" to escape either a single or double quote.

16.The echo and print commands are similar in that they are both constructs, except that print behaves like a PHP function and takes a single argument, while echo can take multiple arguments.

17.The purpose of functions is to separate discrete sections of code into their own, self-contained sections that can be referenced by a single function name.

18.You can make a variable accessible to all parts of a PHP program by declaring it as global.

19.If you generate data within a function, you can convey the data to the rest of the program by returning a value or modifying a global variable.

20.When you combine a string with a number, the result is another string.

Chapter 4 Answers

1. In PHP, TRUE represents the value 1 and FALSE represents NULL, which can be thought of as “nothing” and is output as the empty string.

2. The simplest forms of expressions are literals (such as numbers and strings) and variables, which simply evaluate to themselves.

3. The difference between unary, binary, and ternary operators is the number of operands each requires (one, two, and three, respectively).

4. The best way to force your own operator precedence is to place parentheses around subexpressions to which you wish to give high precedence.

5. Operator associativity refers to the direction of processing (left to right or right to left).

6. You use the identity operator when you wish to bypass PHP’s automatic operand type changing (also called type casting).

7. The three conditional statement types are if, switch, and the ?: operator.

8. To skip the current iteration of a loop and move on to the next one, use a continue statement.

9. Loops using for statements are more powerful than while loops, because they support two additional parameters to control the loop handling.

10.Most conditional expressions in if and while statements are literal (or Boolean) and therefore trigger execution when they evaluate to TRUE. Numeric expressions trigger execution when they evaluate to a nonzero value. String expressions trigger execution when they evaluate to a nonempty string. A NULL value is evaluated as false and therefore does not trigger execution.

Chapter 5 Answers

1. Using functions avoids the need to copy or rewrite similar code sections many times over by combining sets of statements together so that they can be called by a simple name.

2. By default, a function can return a single value. But by utilizing arrays, references, and global variables, any number of values can be returned.

3. When you reference a variable by name, such as by assigning its value to another variable or by passing its value to a function, its value is copied. The original does not change when the copy is changed. But if you reference a variable, only a pointer (or reference) to its value is used, so that a single value is referenced by more than one name. Changing the value of the reference will change the original as well.

4. Scope refers to which parts of a program can access a variable. For example, a variable of global scope can be accessed by all parts of a PHP program.

5. To incorporate one file within another, you can use the include or require directives, or their safer variants, include_once and require_once.

6. A function is a set of statements referenced by a name that can receive and return values. An object may contain zero or many functions (which are then called methods) as well as variables (which are called properties), all combined in a single unit.

7. To create a new object in PHP, use the new keyword like this:

$object = new Class;

8. To create a subclass, use the extends keyword with syntax such as this:

class Subclass extends Parentclass ...

9. To call a piece of initializing code when an object is created, create a constructor method called __construct within the class and place your code there.

10.Explicitly declaring properties within a class is unnecessary, as they will be implicitly declared upon first use. But it is considered good practice as it helps with code readability and debugging, and is especially useful to other people who may have to maintain your code.

Chapter 6 Answers

1. A numeric array can be indexed numerically using numbers or numeric variables. An associative array uses alphanumeric identifiers to index elements.

2. The main benefit of the array keyword is that it enables you to assign several values at a time to an array without repeating the array name.

3. Both the each function and the foreach ... as loop construct return elements from an array; both start at the beginning and increment a pointer to make sure the next element is returned each time; and both return FALSE when the end of the array is reached. The difference is that the each function returns just a single element, so it is usually wrapped in a loop. The foreach ... as construct is already a loop, executing repeatedly until the array is exhausted or you explicitly break out of the loop.

4. To create a multidimensional array, you need to assign additional arrays to elements of the main array.

5. You can use the count function to count the number of elements in an array.

6. The purpose of the explode function is to extract sections from a string that are separated by an identifier, such as extracting words separated by spaces within a sentence.

7. To reset PHP’s internal pointer into an array back to the first element, call the reset function.

Chapter 7 Answers

1. The conversion specifier you would use to display a floating-point number is %f.

2. To take the input string "Happy Birthday" and output the string "**Happy", you could use a printf statement such as:

printf("%'*7.5s", "Happy Birthday");

3. To send the output from printf to a variable instead of to a browser, you would use sprintf instead.

4. To create a Unix timestamp for 7:11am on May 2nd 2016, you could use the command:

$timestamp = mktime(7, 11, 0, 5, 2, 2016);

5. You would use the “w+” file access mode with fopen to open a file in write and read mode, with the file truncated and the file pointer at the start.

6. The PHP command for deleting the file file.txt is:

unlink('file.txt');

7. The PHP function file_get_contents is used to read in an entire file in one go. It will also read them from across the Internet if provided with a URL.

8. The PHP superglobal associative array $_FILES contains the details about uploaded files.

9. The PHP exec function enables the running of system commands.

10.In HTML5 you can use either the XHTML style of tag (such as <hr />) or the standard HTML4 style (such as <hr>). It’s entirely up to you or your company’s coding style.

Chapter 8 Answers

1. The semicolon is used by MySQL to separate or end commands. If you forget to enter it, MySQL will issue a prompt and wait for you to enter it. (In the answers in this section, I’ve left off the semicolon, because it looks strange in the text. But it must terminate every statement.)

2. To see the available databases, type SHOW databases. To see tables within a database that you are using, type SHOW tables. (These commands are case-insensitive.)

3. To create this new user, use the GRANT command like this:

4. GRANT PRIVILEGES ON newdatabase.* TO 'newuser'@'localhost'

IDENTIFIED BY 'newpassword';

5. To view the structure of a table, type DESCRIBE tablename.

6. The purpose of a MySQL index is to substantially decrease database access times by maintaining indexes of one or more key columns, which can then be quickly searched to locate rows within a table.

7. A FULLTEXT index enables natural-language queries to find keywords, wherever they are in the FULLTEXT column(s), in much the same way as using a search engine.

8. A stopword is a word that is so common that it is considered not worth including in a FULLTEXT index or using in searches. However, it does participate in a search when it is part of a larger string bounded by double quotes.

9. SELECT DISTINCT essentially affects only the display, choosing a single row and eliminating all the duplicates. GROUP BY does not eliminate rows, but combines all the rows that have the same value in the column. Therefore, GROUP BY is useful for performing an operation such asCOUNT on groups of rows. SELECT DISTINCT is not useful for that purpose.

10.To return only those rows containing the word Langhorne somewhere in the column author of the table classics, use a command such as:

SELECT * FROM classics WHERE author LIKE "%Langhorne%";

11.When you’re joining two tables together, they must share at least one common column such as an ID number or, as in the case of the classics and customers tables, the isbn column.

Chapter 9 Answers

1. The term relationship refers to the connection between two pieces of data that have some association, such as a book and its author, or a book and the customer who bought the book. A relational database such as MySQL specializes in storing and retrieving such relations.

2. The process of removing duplicate data and optimizing tables is called normalization.

3. The three rules of First Normal Form are:

o There should be no repeating columns containing the same kind of data.

o All columns should contain a single value.

o There should be a primary key to uniquely identify each row.

4. To satisfy Second Normal Form, columns whose data repeats across multiple rows should be removed to their own tables.

5. In a one-to-many relationship, the primary key from the table on the “one” side must be added as a separate column (a foreign key) to the table on the “many” side.

6. To create a database with many-to-many relationship, you create an intermediary table containing keys from two other tables. The other tables can then reference each other via the third.

7. To initiate a MySQL transaction, use either the BEGIN or the START TRANSACTION command. To terminate a transaction and cancel all actions, issue a ROLLBACK command. To terminate a transaction and commit all actions, issue a COMMIT command.

8. To examine how a query will work in detail, you can use the EXPLAIN command.

9. To back up the database publications to a file called publications.sql, you would use a command such as:

mysqldump -u user -ppassword publications > publications.sql

Chapter 10 Answers

1. The standard MySQL function used for connecting to a MySQL database is mysql_connect.

2. The mysql_result function is not optimal when more than one cell is being requested, because it fetches only a single cell from a database and therefore has to be called multiple times, whereas mysql_fetch_row will fetch an entire row.

3. The POST form method is generally better than GET, because the fields are posted directly, rather than being appended to the URL. This has several advantages, particularly in removing the possibility to enter spoof data at the browser’s address bar. (It is not a complete defense against spoofing, however.)

4. To determine the last entered value of an AUTO_INCREMENT column, use the mysql_insert_id function.

5. The PHP function that escapes characters in a string, making it suitable for use with MySQL, is mysql_real_escape_string.

6. The function htmlentities can be used to prevent cross-site scripting injection attacks.

Chapter 11 Answers

1. To connect to a MySQL database with mysqli call the mysqli method, passing the hostname, username, password, and database. A connection object will be returned on success.

2. To submit a query to MySQL using mysqli, ensure you have first created a connection object to a database, and call its query method, passing the query string.

3. When a mysqli error occurs, the error property of the connection object contains the error message. If the error was in connecting to the database, then the connect_error property will contain the error message.

4. To determine the number of rows returned by a mysqli query, use the num_rows property of the result object.

5. To retrieve a specific row from a set of mysqli results, call the data_seek method of the result object, passing it the row number (starting from 0), then call the fetch_array or other retrieval method to obtain the required data.

6. To escape special characters in strings, you can call the real_escape_string method of a mysqli connection object, passing it the string to be escaped.

7. If you neglect to properly close objects created with mysqli methods, your programs carry the risk of running out of memory, especially on high-traffic websites. If there’s a program flow logic error in your code, it also ensures you won’t accidentally access old results.

Chapter 12 Answers

1. The associative arrays used to pass submitted form data to PHP are $_GET for the GET method and $_POST for the POST method.

2. The register_globals setting was the default in versions of PHP prior to 4.2.0. It was not a good idea, because it automatically assigned submitted form field data to PHP variables, thus opening up a security hole for potential hackers who could attempt to break into PHP code by initializing variables to values of their choice.

3. The difference between a text box and a text area is that although they both accept text for form input, a text box is a single line, whereas a text area can be multiple lines and include word wrapping.

4. To offer three mutually exclusive choices in a web form, you should use radio buttons, because checkboxes allow multiple selections.

5. Submit a group of selections from a web form using a single field name by using an array name with square brackets such as choices[], instead of a regular field name. Each value is then placed into the array, whose length will be the number of elements submitted.

6. To submit a form field without the user seeing it, place it in a hidden field using the attribute type="hidden".

7. You can encapsulate a form element and supporting text or graphics, making the entire unit selectable with a mouse-click, by using the <label> and </label> tags.

8. To convert HTML into a format that can be displayed but will not be interpreted as HTML by a browser, use the PHP htmlentities function.

9. You can help users complete fields with data they may have submitted elsewhere using the autocomplete attribute, which prompts the user with possible values.

10.To ensure that a form is not submitted with missing data, you can apply the required attribute to essential inputs.

Chapter 13 Answers

1. Cookies should be transferred before a web page’s HTML, because they are sent as part of the headers.

2. To store a cookie on a web browser, use the set_cookie function.

3. To destroy a cookie, reissue it with set_cookie, but set its expiration date in the past.

4. Using HTTP authentication, the username and password are stored in $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'].

5. The hash function is a powerful security measure, because it is a one-way function that converts a string to a 32-character hexadecimal number that cannot be converted back, and is therefore almost uncrackable.

6. When a string is salted, extra characters (known only by the programmer) are added to it before hash conversion. This makes it nearly impossible for a brute-force dictionary attack to succeed.

7. A PHP session is a group of variables unique to the current user.

8. To initiate a PHP session, use the session_start function.

9. Session hijacking is where a hacker somehow discovers an existing session ID and attempts to take it over.

10.Session fixation is the attempt to force your own session ID onto a server rather than letting it create its own.

Chapter 14 Answers

1. To enclose JavaScript code, you use <script> and </script> tags.

2. By default, JavaScript code will output to the part of the document in which it resides. If it’s in the head, it will output to the head; if in the body, it outputs to the body.

3. You can include JavaScript code from other sources in your documents by either copying and pasting them or, more commonly, including them as part of a <script src='filename.js'> tag.

4. The equivalent of the echo and print commands used in PHP is the JavaScript document.write function (or method).

5. To create a comment in JavaScript, preface it with // for a single-line comment or surround it with /* and */ for a multiline comment.

6. The JavaScript string concatenation operator is the + symbol.

7. Within a JavaScript function, you can define a variable that has local scope by preceding it with the var keyword upon first assignment.

8. To display the URL assigned to the link ID thislink in all main browsers, you can use the two following commands:

9. document.write(document.getElementById('thislink').href)

document.write(thislink.href)

10.The commands to change to the previous page in the browser’s history array are:

11.history.back()

history.go(-1)

12.To replace the current document with the main page at the oreilly.com website, you could use the following command:

document.location.href = 'http://oreilly.com'

Chapter 15 Answers

1. The most noticeable difference between Boolean values in PHP and JavaScript is that PHP recognizes the keywords TRUE, true, FALSE, and false, whereas only true and false are supported in JavaScript. Additionally, in PHP TRUE has a value of 1 and FALSE is NULL; in JavaScript they are represented by true and false, which can be returned as string values.

2. Unlike PHP, no character is used (such as $) to define a JavaScript variable name. JavaScript variable names can start with and contain any uppercase and lowercase letters as well as underscores; names can also include digits, but not as the first character.

3. The difference between unary, binary, and ternary operators is the number of operands each requires (one, two, and three, respectively).

4. The best way to force your own operator precedence is to surround the parts of an expression to be evaluated first with parentheses.

5. You use the identity operator when you wish to bypass JavaScript’s automatic operand type changing.

6. The simplest forms of expressions are literals (such as numbers and strings) and variables, which simply evaluate to themselves.

7. The three conditional statement types are if, switch, and the ?: operator.

8. Most conditional expressions in if and while statements are literal or Boolean and therefore trigger execution when they evaluate to TRUE. Numeric expressions trigger execution when they evaluate to a nonzero value. String expressions trigger execution when they evaluate to a nonempty string. A NULL value is evaluated as false and therefore does not trigger execution.

9. Loops using for statements are more powerful than while loops, because they support two additional parameters to control loop handling.

10.The with statement takes an object as its parameter. Using it, you specify an object once; then for each statement within the with block, that object is assumed.

Chapter 16 Answers

1. JavaScript functions and variable name are case-sensitive. The variables Count, count, and COUNT are all different.

2. To write a function that accepts and processes an unlimited number of parameters, access parameters through the arguments array, which is a member of all functions.

3. One way to return multiple values from a function is to place them all inside an array and return the array.

4. When defining a class, use the this keyword to refer to the current object.

5. The methods of a class do not have to be defined within a class definition. If a method is defined outside the constructor, the method name must be assigned to the this object within the class definition.

6. New objects are created via the new keyword.

7. You can make a property or method available to all objects in a class without replicating the property or method within the object by using the prototype keyword to create a single instance, which is then passed by reference to all the objects in a class.

8. To create a multidimensional array, place subarrays inside the main array.

9. The syntax you would use to create an associative array is key : value, within curly braces, as in the following:

10.assocarray =

11.{

12. "forename" : "Paul",

13. "surname" : "McCartney",

14. "group" : "The Beatles"

}

15.A statement to sort an array of numbers into descending numerical order would look like this:

numbers.sort(function(a, b){ return b - a })

Chapter 17 Answers

1. You can send a form for validation prior to submitting it by adding the JavaScript onsubmit attribute to the <form> tag. Make sure that your function returns true if the form is to be submitted and false otherwise.

2. To match a string against a regular expression in JavaScript, use the test method.

3. Regular expressions to match characters not in a word could be any of /[^\w]/, /[\W]/, /[^a-zA-Z0-9_]/, and so on.

4. A regular expression to match either of the words fox or fix could be /f[oi]x/.

5. A regular expression to match any single word followed by any nonword character could be /\w+\W/g.

6. A JavaScript function using regular expressions to test whether the word fox exists in the string "The quick brown fox" could be:

document.write(/fox/.test("The quick brown fox"))

7. A PHP function using a regular expression to replace all occurrences of the word the in "The cow jumps over the moon" with the word my could be:

$s=preg_replace("/the/i", "my", "The cow jumps over the moon");

8. The HTML attribute used to precomplete form fields with a value is value, which is placed within an <input> tag and takes the form value="value".

Chapter 18 Answers

1. It’s necessary to write a function for creating new XMLHttpRequest objects, because Microsoft browsers use two different methods of creating them, while all other major browsers use a third. By writing a function to test the browser in use, you can ensure that code will work on all major browsers.

2. The purpose of the try ... catch construct is to set an error trap for the code inside the try statement. If the code causes an error, the catch section will be executed instead of a general error being issued.

3. An XMLHttpRequest object has six properties and six methods (see Tables 18-1 and 18-2).

4. You can tell that an Ajax call has completed when the readyState property of an object has a value of 4.

5. When an Ajax call successfully completes, the object’s status will have a value of 200.

6. The responseText property of an XMLHttpRequest object contains the value returned by a successful Ajax call.

7. The responseXML property of an XMLHttpRequest object contains a DOM tree created from the XML returned by a successful Ajax call.

8. To specify a callback function to handle Ajax responses, assign the function name to the XMLHttpRequest object’s onreadystatechange property. You can also use an unnamed, inline function.

9. To initiate an Ajax request, an XMLHTTPRequest object’s send method is called.

10.The main differences between an Ajax GET and POST request are that GET requests append the data to the URL and not as a parameter of the send method, and POST requests pass the data as a parameter of the send method and require the correct form headers to be sent first.

Chapter 19 Answers

1. To import one style sheet into another, you use the @import directive like this:

@import url('styles.css');

2. To import a style sheet into a document, you can use the HTML <link> tag, like this:

<link rel='stylesheet' type='text/css' href='styles.css'>

3. To directly embed a style into an element, use the style attribute, like this:

<div style='color:blue;'>

4. The difference between a CSS ID and a CSS class is that an ID is applied to only a single element, whereas a class can be applied to many elements.

5. In a CSS declaration, ID names are prefixed with a # character (e.g., #myid), and class names with a . character (e.g., .myclass).

6. In CSS, the semicolon is used as a separator between declarations.

7. To add a comment to a style sheet, you enclose it between /* and */ opening and closing comment markers.

8. In CSS, you can match any element using the * universal selector.

9. To select a group of different elements and/or element types in CSS, you place a comma between each element, ID, or class.

10.Given a pair of CSS declarations with equal precedence, to make one have greater precedence over the other, you append the !important declaration to it, like this:

p { color:#ff0000 !important; }

Chapter 20 Answers

1. The CSS3 operators ^=, $=, and *= match the start, end, or any portion of a string, respectively.

2. The property you use to specify the size of a background image is background-size, like this:

background-size:800px 600px;

3. You can specify the radius of a border using the border-radius property, like this:

border-radius:20px;

4. To flow text over multiple columns, you use the column-count, column-gap, and column-rule properties or their browser-specific variants, like this:

5. column-count:3;

6. column-gap :1em;

column-rule :1px solid black;

7. The four functions with which you can specify CSS colors are hsl, hsla, rgb, and rgba; for example:

color:rgba(0%,60%,40%,0.4);

8. To create a gray text shadow under some text, offset diagonally to the bottom right by 5 pixels, with a blurring of 3 pixels, you would use this declaration:

text-shadow:5px 5px 3px #888;

9. You can indicate that text is truncated with an ellipsis using this declaration:

text-overflow:ellipsis;

10.You include a Google Web Font in a web page by first selecting it from http://google.com/fonts. Then assuming, for example, you chose Lobster, include it in a <link> tag, like this:

11.<link href='http://fonts.googleapis.com/css?family=Lobster'

rel='stylesheet' type='text/css'>

and also refer to the font in a CSS declaration such as this:

h1 { font-family:'Lobster', arial, serif; }

12.The CSS declaration you would you use to rotate an object by 90 degrees is:

transform:rotate(90deg);

13.To set up a transition on an object so that when any of its properties are changed the change will transition immediately in a linear fashion over the course of half a second, you would use this declaration:

transition:all .5s linear;

Chapter 21 Answers

1. The O function returns an object by its ID, the S function returns the style property of an object, and the C function returns an array of all objects that access a given class.

2. You can modify a CSS attribute of an object using the setAttribute function, like this:

myobject.setAttribute('font-size', '16pt')

You can also (usually) modify an attribute directly (using slightly modified property names where required), like this:

myobject.fontSize = '16pt'

3. The properties that provide the width and height available in a browser window are window.innerHeight and window.innerWidth.

4. To make something happen when the mouse passes over and out of an object, attach to the onmouseover and onmouseout events.

5. To create a new element, use code such as:

elem = document.createElement('span')

To add the new element to the DOM, use code such as:

document.body.appendChild(elem)

6. To make an element invisible, set its visibility property to hidden (or visible to restore it again). To collapse an element’s dimensions to zero, set its display property to none (the value block is one way to restore it).

7. To set a single event at a future time, call the setTimeout function, passing it the code or function name to execute and the time delay in milliseconds.

8. To set up repeating events at regular intervals, use the setInterval function, passing it the code or function name to execute and the time delay between repeats in milliseconds.

9. To release an element from its location in a web page to enable it to be moved around, set its position property to relative, absolute, or fixed. To restore it to its original place, set the property to static.

10.To achieve an animation rate of 50 frames per second, you should set a delay between interrupts of 20 milliseconds. To calculate this value, divide 1,000 milliseconds by the desired frame rate.

Chapter 22 Answers

1. The new HTML5 element for drawing graphics in a web browser is the canvas element, created using the <canvas> tag.

2. You need to use JavaScript to access many of the new HTML5 technologies such as the canvas and geolocation.

3. To incorporate audio or video in a web page, you use the <audio> or <video> tags.

4. In HTML5, local storage offers far greater access to local user space than cookies, which are limited in the amount of data they can hold.

5. In HTML5 you can set up web workers to carry on background tasks for you. These workers are simply sections of JavaScript code.

Chapter 23 Answers

1. To create a canvas element in HTML, use a <canvas> tag and specify an ID that JavaScript can use to access it, like this:

<canvas id='mycanvas'>

2. To give JavaScript access to a canvas element, ensure the element has been given an ID such as mycanvas, and then use the document.getElementdById function (or the O function from the OSC.js file supplied on the companion website) to return an object to the element. Finally, call getContext on the object to retrieve a 2D context to the canvas, like this:

3. canvas = document.getElementById('mycanvas')

context = canvas.getContext('2d')

4. To start a canvas path, issue the beginPath method on the context. After creating a path, you close it by issuing closePath on the context, like this:

5. context.beginPath()

6. // Path creation commands go here

context.closePath()

7. You can extract the data from a canvas using the toDataURL method, which can then be assigned to the src property of an image object, like this:

image.src = canvas.toDataURL()

8. To create a gradient fill (either radial or linear) with more than two colors, specify all the colors required as stop colors assigned to a gradient object you have already created, and assign them each a starting point as a percent value of the complete gradient (between 0 and 1), like this:

9. gradient.addColorStop(0, 'green')

10.gradient.addColorStop(0.3, 'red')

11.gradient.addColorStop(0,79, 'orange')

gradient.addColorStop(1, 'brown')

12.To adjust the width of drawn lines, assign a value to the lineWidth property of the context, like this:

context.lineWidth = 5

13.To ensure that future drawing takes place only within a certain area, you can create a path and then call the clip method.

14.A complex curve with two imaginary attractors is called a Bézier curve. To create one, call the bezierCurveTo method, supplying two pairs of x and y coordinates for the attractors, followed by another pair for the end point of the curve. A curve is then created from the current drawing location to the destination.

15.The getImageData method returns an array containing the specified pixel data, with the elements consecutively containing the red, green, blue, and alpha pixel values, so four items of data are returned per pixel.

16.The transform method takes six arguments (or parameters), which are in order: horizontal scale, horizontal skew, vertical skew, vertical scale, horizontal translate, and vertical translate. Therefore, the arguments that apply to scaling are numbers 1 and 4 in the list.

Chapter 24 Answers

1. To insert audio and video into an HTML5 document, use the <audio> and <video> tags.

2. To guarantee maximum audio playability on all platforms, you should use the OGG codec plus either the ACC or MP3 codec.

3. To play and pause HTML5 media playback, you can call the play and pause methods of an audio or video element.

4. To support media playback in a non-HTML5 browser, you can embed a Flash audio or video player inside any audio or video element, which will be activated if HTML5 media playing is not supported.

5. To guarantee maximum video playability on all platforms, you should use the MP4/H.264 codec, and the OGG/Theora or VP8 codec to support the Opera browser.

Chapter 25 Answers

1. To request geolocation data from a web browser, you call the following method, passing the names of two functions you have written for handling access or denial to the data:

navigator.geolocation.getCurrentPosition(granted, denied)

2. To determine whether or not a browser supports local storage, test the typeof property of the localStorage object, like this:

3. if (typeof localStorage == 'undefined')

// Local storage is not available}

4. To erase all local storage data for the current domain, you can call the localStorage.clear method.

5. Web workers communicate with a main program most easily using the postMessage method to send information, and by attaching to the web worker object’s onmessage event to retrieve it.

6. To inform a web browser that the document can be run offline as a local web app, create a file to use as a manifest; in that file, list the files required by the application, then link to the file in the <html> tag, like this:

<html manifest='filename.appcache'>

7. You can prevent the default action of disallowing drag and drop for the events that handle these operations, by issuing a call to the event object’s preventDefault method in your ondragover and ondrop event handlers.

8. To make cross-document messaging more secure, you should always supply a domain identifier when posting messages, and check for that identifier when receiving them, like this for posting:

postMessage(message, 'http://mydomain.com')

And this for receiving:

if (event.origin) != 'http://mydomain.com') // Disallow

You can also encrypt or obscure communications to discourage injection or eavesdropping.

9. The purpose of microdata is to make information more easily understandable by computer programs, such as search engines.