Appendix D. JavaScript – Hello! HTML5 & CSS3: A user-friendly reference guide

Appendix D. JavaScript

The main focus of this book is HTML5 and CSS3, but to take full advantage of many of the features of these two technologies you’ll end up using JavaScript quite a lot. The APIs in HTML5 are accessible through JavaScript, and the techniques you’ve seen for detecting HTML5 and CSS3 support depend on JavaScript.

The goal of this appendix isn’t to teach you to be a great JavaScript programmer even if you’ve never programmed before, but to teach you enough syntax that you can recognize what the examples in the book are trying to do and enough practical knowledge that you can experiment on your own to learn more.

Setting up an interactive console

In this appendix, you’ll learn by doing. To do that, you need a way to type JavaScript code into your browser and immediately see the results. Most modern browsers come with a built-in facility for this as part of their developer tools.

Chrome (and Safari)

Chrome and Safari are both based on the WebKit browsing engine, so apart from some stylistic differences, their developer tools are identical.

Access the developer tools by right-clicking any element on the page and selecting the Inspect Element option.

A panel opens at the bottom of the browser window like the one shown here.

Look for the Console button in the toolbar across the top of the panel, and click it.

You should see a command prompt > and a cursor. You can type in JavaScript and see it executed immediately.

Here are the key features of the Chrome console. All the examples in this appendix should work in Chrome.

Firefox

Thanks to its extensible nature, Firefox has long relied on add-ons to fill the developer tool gap, notably Firebug (discussed in a moment). Newer versions of Firefox (since version 8) have developer tools built in.

Access these tools from the main menu under Web Developer. For now, either select Web Console or press Ctrl+Shift+K.

The console monitors four things by default: network requests (Net), CSS, JavaScript (JS), and console logging (Web Developer or Logging in newer versions). You can turn them on and off individually by clicking the buttons along the top of the console. In this appendix, you may find it helpful to turn off everything except JavaScript and console logging.

The next figure shows the key details of the Firefox console. Most of the screenshots in the following sections were taken using Firefox.

Other browsers

Several other browsers ought to work equally well. Here’s how you get to the console in them:

  • Internet Explorer—Press F12, or look for developer tools in the Page menu.
  • Opera—Right-click the page, and choose Inspect Element from the context menu.
  • Firefox with Firebug—Press F12, or right-click and select Inspect with Firebug from the context menu.

Arithmetic and variables

A computer program is based on math. It boils down to a sequence of mathematical operations on a collection of numbers. If you’ve always been bad at math, don’t let this frighten you: programming—the act of composing a program—has as much in common with writing a story as it does with solving math problems (albeit a story written with unusually strict grammar and far more punctuation then you’re used to). Think of it as an obscure subgenre of science fiction. But the simplest programs that can be written are basic mathematical statements, so we’ll start with them. Open the JavaScript console in your preferred web browser, and follow along with the examples.

Arithmetic

In this section, you’ll learn how basic arithmetic operations are represented in JavaScript. The examples are all shown in the Firefox Web Console, but you should see the same results in any other browser.

Basic addition, subtraction, multiplication, and division are written in much the same way as they were in your high school book. The asterisk (*) is used to indicate multiplication and the forward slash (/) division. Expressions and their values are shown in the console output. Try typing a few expressions and pressing Enter.

Programmers refer to numbers as operands and symbols as operators. The entire combination is called an expression. A sequence of expressions terminated by a semicolon is a statement. The following diagram should help you get the vocabulary straight.

Any number of operands and operators can be chained together, but they’re not evaluated left to right. Some operators are more important than others and are always evaluated first.

In the first example, the multiplication is performed before the addition, so the result is 8. The terminology is that multiplication has a higher precedence than addition.

To explicitly control the order of evaluation, you can use parentheses to group operations. The second example shows a forced left-to-right evaluation.

In addition to adding numbers, the + operator can add text together. Text values in a JavaScript program are referred to as strings. Strings are always demarcated by either double or single quotes—it doesn’t matter which as long they’re used in pairs, as the first two examples show.

Strings and numbers can be added to each other in certain circumstances, although using any of the other arithmetic operators with strings leads to a not-a-number (NaN) result.

If the string is also a number, it can be used with normal arithmetic operations, but the results won’t always be what you expect. JavaScript makes up its own mind about whether you mean arithmetic or string addition.

In the first two examples, string addition is used rather than numeric, because addition can be performed on both numbers and strings and one of the operands is a string.

The multiplication operation can only be used with numbers, so the strings are converted automatically to numbers.

Comparisons

Comparisons are operators that produce a true or false value, otherwise known as a Boolean value. Comparison operators are crucial when it comes to branching and looping (see “Branching and looping”). There are general-purpose comparison operators as well as several operators that are intended for Boolean values. The three main Boolean operators are as follows:

&& AND Returns true if both operands are true
|| OR Returns true if either operand is true
! NOT Returns true if its operand is false

Experiment with these operators in the console until you’re comfortable with these meanings.

You can compare two values for equality with these operators:

== EQUAL Returns true if both operands are the same
!= NOT EQUAL Returns true if the operands are different

Note that if you begin comparing things of different types, you may get unexpected results.

Because JavaScript helpfully converts types for you, the equality operators aren’t always reliable.

=== IDENTICAL Returns true if the operands are the same type and have the same value

Again, if you compare things of different types, you may get unexpected results. In the example here, 2 == "2" (comparing an integer with a string) evaluates to true, since JavaScript converts the integer 2 to a string "2" before comparison. But 2 === "2" evaluates to false because an integer is not a string.

You can check whether something is smaller or larger than another thing:

< LESS THAN Returns true if the first value is less than the second value
> GREATER THAN Returns true if the first value is greater than the second value

When you compare strings with < and >, JavaScript takes the numeric value of the characters and compares them. This means H is greater than C, but H is less than c, because lowercase letters are all larger than uppercase letters for comparison purposes. As with the arithmetic operations you saw earlier, bugs can occur if you’re expecting to compare numbers but in reality are comparing strings. JavaScript doesn’t complain in either case.

You can also compare smaller and larger and equal to:

<= LESS THAN OR EQUAL TO Returns true if the first value is less than or equal to the second value
>= GREATER THAN OR EQUAL TO Returns true if the first value is greater than or equal to the second value

Now you can perform arithmetic and comparisons, but what can you do with them? Comparisons are used extensively in branching and looping, which we’ll examine in the section “Branching and looping,” but if you compare the same fixed values in your program you’ll see the same results every time. You need to store variable factors in the program so you can provide different results according to different starting conditions: you need variables.

Variables

A variable is a place to store the result of a calculation. If you remember any of your high school algebra, the concept of a variable ought to be somewhat familiar. You may remember algebra problems something like this:

5 = 2 + x

In math, working out the variable’s value results in the answer. In this case, it’s clear that x = 3. But in JavaScript, you express it like this:

var x = 5 - 2;

This code is saying “Create a storage space called x; calculate the result of 5 – 2; store the result in the storage space called x. The var keyword allocates a variable.”

After you’ve stored a value in a variable, you can use it in another calculation, as shown here. First a value is assigned to x and then to y, and then the variables x and y are used in a calculation that assigns a value to z.

The console.log(z) statement is an example of calling a method on an object. For now, you don’t need to know what that means (you’ll learn more in the section “Functions and objects”); just be aware that it prints out the current value of whatever variable you put in the brackets.

Unlike in algebra, you have to define all the variables that appear on the right side of the equals sign before you use them. The sequence of operations here shows what happens if you don’t.

When JavaScript can’t understand your code or is unable to execute it, an error occurs. Usually this immediately stops the execution of whatever program is running. You can see in this example that the error that c isn’t defined wasn’t discovered until b was defined, because the initial error stopped execution.

After you create a variable, you can assign it a new value at any time. When you use the variable in a calculation that assigns a new value to itself, remember that the assignment operator sets the new value, and that always happens last—the value isn’t updated until the end of the calculation.

If you put a number in a variable, nothing stops you from adding a string to it. But as with previous situations where JavaScript is equally happy with a string or a number, this can lead to confusing errors.

Special operators for variables

Two operators that won’t be familiar to you from school arithmetic are the post-increment (++) and post-decrement (--) operators. They increase and decrease, respectively, the value of a number by one. Post means they perform the change after the value has been used in an expression.

Study the sequence of operations in this screenshot. Notice that the values assigned to a and b are those of i before the increment or decrement.

You also need to know about the += operator and its relatives.

The need to store the result of an expression into a variable when it’s one of the operands is so common that a shortcut is built into JavaScript. Instead of writing

a = a + b;

you can write

a += b;

This works for the other arithmetic operators, as you can see in the screenshot.

In this section, you’ve learned how to do calculations and comparisons and store the results in variables. That is fundamental to writing programs but not very useful by itself. You need to be able to take different actions depending on the results, or perform actions repeatedly to make it worth your while to write a program in the first place.

Branching and looping

If your program did some calculations and always produced the same output, there wouldn’t be a point to it. A program can’t do much unless it can make decisions based on the variables being passed into it. When a program executes one block of code rather than another based on the value of a variable, that’s what we call branching. Looping is a related concept: executing a block of code multiple times. In this section, you’ll step back from the console for a few pages and learn about the various branching and looping concepts in JavaScript so that in the following sections you can see how they’re used.

The term branching, unsurprisingly, comes from an analogy to a tree branch. Imagine you’re walking along the branch of a tree: eventually you come to a point where it divides into two. You can choose to go up one branch or the other one. That’s all branching is in programming—choosing to go one way or another. The simplest branching construct is the if statement.

If you need to check for more than one condition, you can nest the if ... else statements.

An alternative to if ... then ... else is the switch statement. It lets you choose from a long list of alternatives based on the value of a variable. It doesn’t allow the flexibility of if ... then ... else in comparison operations but does offer a more easily comprehensible way of presenting multiple choices.

That’s all you need to know about branching, so on to looping. Looping lets you repeat an operation multiple times. The most common loop is for.

This screenshot shows the output in the console from the for loop. It logs 10 lines, counting up from 0 to 9. This is the normal programmer way of counting 10 things, starting at 0, so get used to it!

It’s also normal to use the loop index variable, i in this case, to modify the code’s behavior on each iteration through the loop.

An alternative to the for loop is the while loop. As you can see from the following diagram, it has all the same features as the for loop, but the arrangement is slightly different.

This screenshot shows the output in the console from the while loop. Incrementing by two each time through the loop means only five iterations.

You would normally use a while loop when you weren’t sure how many iterations (trips through the loop) were required. Whereas the for loop always counts from something to something, a while loop does as many or as few iterations as required. For instance, if you had a collection of 10,000 numbers and wanted to find the first one that was even, you would use a while loop because you would expect to find an even number in the first few you looked at.

There’s a variation on the while loop called the do ... while loop. As you can see in the next diagram, it’s similar to the while loop; the main difference is that the test to see whether the loop should continue is at the end.

The previous do ... while loop produces exactly the same output as the earlier while loop. For a large number of iterations, this will always be true. The main difference comes when the while loop may not be executed at all.

Following on the left is a while loop; on the right is a do ... while loop with the same code block and test expression. You can see from the console output that the while loop doesn’t execute its code block because the test expression is false. But the do ... while loop does execute its code block, because the test expression isn’t checked until the end of the loop.

The loop never executes if the condition expression evaluates to false. The loop always executes at least once.

Functions and objects

So far, we’ve covered basic arithmetic operations and comparisons, variables in which to store results of those operations, and structures that allow you to control program flow based on variables and comparisons. Next you need to learn how to structure those components into complete programs. This is where functions and objects come in.

Functions

A function takes input, transforms it in some way, and produces output. Here’s an example.

This function is short enough that you can experiment with it in the console. To run the code in the function (or call the function, as a developer would say), you use the function name followed by parentheses containing the argument you want to pass. The argument is assigned to the parameter within the function body.

It’s worth explaining that again: the parameter is the placeholder in the function definition. The argument is the value passed into the function when it’s called. In practice, people ignore this subtle distinction and use the two terms interchangeably; we’ll try to keep them straight, but don’t worry about the difference too much.

Real functions generally contain more complex logic, but the examples here are short so it’s feasible for you to type them into the console. Here’s a slightly more complex example.

When you write your own functions, it’s more common to put each operation on a single line, like this:

function evenMe(n) {
    if (n % 2 == 1) {
        return n + 1;
    } else {
        return n;
    }
}

But JavaScript, like HTML, doesn’t care about whitespace; that just makes it easier for humans to read. It works no matter how many lines it takes up, but for the console you need to get everything onto one line. Functions can take more than one argument.

Here’s the previous function written in a more conventional style to make it easier to read. The function rounds the argument n up to the next multiple of a:

function baseMe(n,a) {
    while (n % a != 0) {
        n++;
    };
    return n;
}

Precedence, which you saw in the simple arithmetic examples earlier, also applies with functions. This is important when you want to pass the result of one function as an argument to another.

Functions are evaluated from the inside out. This probably seems intuitive; but to confuse the situation, it’s possible to pass functions as arguments to other functions.

Here’s a simple function that expects a function as a parameter:

function applyMe(f,n)
  {return f(n);}

To pass the function as an argument, you specify the function name without adding parentheses.

Passing functions as arguments is a common pattern in calling HTML5 APIs. It’s also common to declare simple, single-use functions directly. This is called an inline function: it’s declared and then thrown away. You can use it only within the function it’s being passed to, not elsewhere in your program, because there’s no label to refer to it.

That’s all you need to know about functions—time to move on to objects.

Objects

Functions let you group your code into convenient units that can then be called in your program, but you’ll also want to group data and functions together. In JavaScript you do this with objects. In loose terms, an object is a collection of stuff. The stuff can be variables, functions, and other objects. JavaScript has several built-in objects, HTML provides another set of objects, and the browser still more. You can also create your own objects; let’s start with that.

The simplest way to create an object is with an object literal. An empty object is a pair of braces. The object can contain variables and functions, but when they’re part of an object they’re referred to as properties and methods.

In JavaScript, you can access a property or method on an object by using a period (.) followed by a label. You can create properties and methods by assigning a value, as shown here.

This is the same code in an easier-to-read format:

var myObject = {};
myObject.myProperty = 2;
myObject.myMethod = function(n) {
        return n * 3;
}

You can then call the method, passing in the property like this:

myObject.myMethod(myObject.myProperty);

Now that you have an object to play with, it’s time to learn about the final type of loop: for ... in. The following screenshot of the console shows a for ... in loop in action on the myObject object just created.

F or ... in loops through the properties and methods of an object. The variable prop is set to the label associated with the property or method. You’ll see it used most often in scripts that check to see if a browser supports certain HTML5 features. Note that the syntax myObject ['myProperty'] is an alternative way of accessing the myProperty method. This alternative approach is handy for use inside for ... in loops.

Before we finish with objects, it’s important to know that variables that refer to objects behave slightly differently than variables that refer to normal values like numbers. To see the difference, let’s do a little experiment in the console.

  1. Create a variable a, and give it the value 2.
  2. Create a variable b, and give it the value of a.
  3. Set the variable b to have a value of 4 instead.

Notice that after you do this, the value of a is unchanged. Setting b to have a value of a doesn’t create any sort of relationship between them. The value contained in a is copied into b.

Now try a similar sequence of operations with two variables that refer to objects. Notice that after assigning myObject as the value of myOtherObject, changing the value of myOtherObject.myProperty also changes the value of myObject.myProperty. This is because assigning the object to another variable creates two variables that refer to the same object.

There are several other features of objects, as well as a few different ways to create them, but you won’t need to know them for this book. Just bear in mind that whenever you see periods, you’re almost always looking at objects with properties and methods.

How JavaScript fits into HTML

The point of learning JavaScript is using it in browsers to do things with web pages. In this section, you’ll learn how to get your JavaScript into HTML. You can do this three primary ways: inline in a <script> element, linked in a separate file, and inline in an event handler. Let’s look at each in turn.

Inline <script> element

The most straightforward way to add JavaScript to your web page is to include it inside a <script> element. Here’s a simple example:

<!DOCTYPE html>
<html>
<head>
    <title>Inline script</title>
</head>
<body>
    <script>
        window.alert("Inline script!");
    </script>
</body>
</html>

If you create a web page using this code and load it in your browser, you should see something like the following screenshot (if you’re using IE, you may need to click the warning bar to allow JavaScript in a local file).

After the previous section, you should have noticed that window is an object and alert is a method. This is built-in functionality provided by the browser.

JavaScript linked in a file

In the same way that CSS can be kept in a separate file so it can be used in more than one web page, so can JavaScript. When you load the page in your browser, it looks much the same as the previous example.

For this you need two files. The first is an HTML page:

<!DOCTYPE html>
<html>
<head>
    <title>Linked script</title>
</head>
<body>
    <script src="myscript.js"></script>
</body>
</html>

Then you need a file called myscript.js containing this line of code:

window.alert('Linked script!');

Inline event handlers

The final way to include JavaScript in a page is through an inline event handler. Events are things that can happen in a page, such as a user clicking a button. You’ll learn more about them in the section “Events”; for now, you just need to know that you can create a handler for a click event by adding an onclick attribute to an element. This is what the page looks like.

When you click the button, the alert pops up. Here’s the code:

<!DOCTYPE html>
<html>
<head>
    <title>Inline event handler</title>
</head>
<body>
    <button onclick="window.alert('Inline event!');">
        Click me
    </button>
</body>
</html>

You should notice two things about this code. First, no <script> elements were required: the JavaScript is directly in the markup. Second, the quotes around the argument to alert are single quotes, unlike the double quotes used in the previous example. In JavaScript, you can use either single or double quotes—it doesn’t make any difference as long as you start and end a given string with the same type of quote. But double quotes are used in the HTML for the attribute value, so using double quotes in the JavaScript would make the HTML invalid.

The DOM

The Document Object Model (usually referred to as the DOM) is the way you access a web page through JavaScript. As the name implies, it’s based on an object called window. You already used the alert method of the window object in the previous section. The window object contains properties and methods provided by the browser, the most important of which is the document object. The document object contains properties and methods provided by the web page. To experiment with the document object, create a simple web page:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>DOM Example</title>
</head>
<body>
    <div id="first">
        <h1>First div</h1>
        <p>Paragraph in
           first div</p>
    </div>
    <div id="second">
        <h1>Second div</h1>
    </div>
</body>
</html>

Open the console, and type in this code:

document.getElementById('first');

As you can see, the getElementById method returns an object. This object also has methods and properties that you can call:

var d =

document.getElementById('first');
console.log(d.innerHTML);

The elements inside the <div> can also be accessed through methods and properties of the element. This code grabs the first child of the <div>:

var h = d.children[0]

The DOM isn’t just a way to access the document. You can also use it to modify the page. Here’s a quick example.

Here’s the code in more detail:

Events

You saw an event handler in “How JavaScript fits into HTML”—in that case, an inline event handler. A handler is a function that’s called when an event happens (when the event fires). In this section, you’ll see how to deal with events in an external JavaScript file. When you’re attaching handlers from an external JavaScript file, you need to use the DOM.

Use the simple page you created for exploring the DOM in the previous section, but add a reference to an external JavaScript file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>DOM Example</title>
    <script src="events.js"></script>
</head>
<body>
    <div id="first">
         <h1>First div</h1>
         <p>Paragraph in first div</p>
    </div>
    <div id="second">
        <h1>Second div</h1>
    </div>
</body>
</html>

Of course, you also need to create the JavaScript file. Start with this code in it:

var d = document.getElementById('first');
console.log(d.innerHTML);

If you load the page now, you’ll see this in the console.

This happens because at the point where the JavaScript executes, no element has the ID first. The JavaScript is executed as soon as it’s referenced, in the <head> element. You need the JavaScript to await execution until after the document is loaded. Fortunately, there’s an event for just such a scenario.

Wrap the code you want to run in a function:

function go() {
    var d = document
        .getElementById('first');
    console.log(d.innerHTML);
}

Then use the addEventListener method to attach your function as a handler for the window’s load event:

window.addEventListener('load', go);

You can see in the console that the code now runs as expected. Notice that a function is being passed as an argument, as discussed earlier.

Now let’s extend this example to add a button element and then add a click handler to the element. The following screenshots show the page before and after clicking the button.

This is the code to put in the events.js file:

The final thing you need to be aware of is event bubbling. When an event occurs, such as a click event, it bubbles up the document tree. This means the click event is fired from the element where the event occurred all the way up to the document root. This example attaches to the document a click handler that determines what type of element was clicked.

Returning to the example, edit events.js one more time:

Any function added as an event handler receives the event object as a parameter . The target property of the event object is the element where the event originated. The element object has a nodeName property that tells you the type of element clicked. You attach click_handler to the document to handle all click events .

The main benefit of this approach is that it reduces the number of event listeners required. This can reduce memory and processing requirements for large and complex pages. You’ll see it used frequently in large-scale web applications.

Further reading

For a detailed discussion of the differences between event handling in IE and all the other browsers, refer to quirksmode.org: www.quirksmode.org/js/introevents.html.

For a complete reference of all the methods and properties of the DOM, check out the Mozilla Developer Network: https://developer.mozilla.org/en/DOM/.

For an alternative introduction to JavaScript, try “Thau’s JavaScript Tutorial”: www.webmonkey.com/2010/02/javascript_tutorial/.