BUY THIS BOOK
Add to Cart

Print Book $39.99


Add to Cart

Print+PDF $51.99

Add to Cart

PDF $31.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £24.99

What is this?

Looking to Reprint or License this content?


JavaScript: The Missing Manual
JavaScript: The Missing Manual By David Sawyer McFarland
July 2008
Pages: 543

Cover | Table of Contents


Table of Contents

Chapter 1: Writing Your First JavaScript Program
By itself, HTML doesn't have any smarts: It can't do math, it can't figure out if someone has correctly filled out a form, and it can't make decisions based on how a Web visitor interacts with it. Basically, HTML lets people read text, look at pictures, and click links to move to other Web pages with more text and pictures. In order to add intelligence to your Web pages so they can respond to your site's visitors, you need JavaScript.
JavaScript lets a Web page react intelligently. With it, you can create smart Web forms that let visitors know when they've forgotten to include necessary information; you can make elements appear, disappear, or move around a Web page (see ); you can even update the contents of a Web page with information retrieved from a Web server—without having to load a new Web page. In short, JavaScript lets you make your Web sites more engaging and effective.
For a lot of people, the word "computer programming" conjures up visions of super-intelligent nerds hunched over keyboards, typing nearly unintelligible gibberish for hours on end. And, honestly, some programming is just like that. Programming can seem like complex magic that's well beyond the average mortal. But many programming concepts aren't difficult to grasp, and as programming languages go, JavaScript is relatively friendly to nonprogrammers.
Figure : JavaScript lets Web pages respond to visitors. On Amazon.com, mousing over the "Gifts and Wish Lists" link opens a tab that floats above the other content on the page and offers additional options.
Still, JavaScript is more complex than either HTML or CSS, and programming often is a foreign world to Web designers; so one goal of this book is to help you think more like a programmer. Throughout this book you'll learn fundamental programming concepts that apply whether you're writing JavaScript, ActionScript, or even writing a desktop program using C++. More importantly, you'll learn how to approach a programming task so you'll know exactly what you want to do before you start adding JavaScript to a Web page.
Many Web designers are immediately struck by the strange symbols and words used in JavaScript. An average JavaScript program is sprinkled with symbols ({ } [ ] ; , ( ) !=) and full of unfamiliar words (var, null, else if). It's like staring at a foreign language, and in many ways learning a programming language is a lot like learning another language. You need to learn new words, new punctuation, and understand how to put them together so you can communicate successfully.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introducing Programming
For a lot of people, the word "computer programming" conjures up visions of super-intelligent nerds hunched over keyboards, typing nearly unintelligible gibberish for hours on end. And, honestly, some programming is just like that. Programming can seem like complex magic that's well beyond the average mortal. But many programming concepts aren't difficult to grasp, and as programming languages go, JavaScript is relatively friendly to nonprogrammers.
Figure : JavaScript lets Web pages respond to visitors. On Amazon.com, mousing over the "Gifts and Wish Lists" link opens a tab that floats above the other content on the page and offers additional options.
Still, JavaScript is more complex than either HTML or CSS, and programming often is a foreign world to Web designers; so one goal of this book is to help you think more like a programmer. Throughout this book you'll learn fundamental programming concepts that apply whether you're writing JavaScript, ActionScript, or even writing a desktop program using C++. More importantly, you'll learn how to approach a programming task so you'll know exactly what you want to do before you start adding JavaScript to a Web page.
Many Web designers are immediately struck by the strange symbols and words used in JavaScript. An average JavaScript program is sprinkled with symbols ({ } [ ] ; , ( ) !=) and full of unfamiliar words (var, null, else if). It's like staring at a foreign language, and in many ways learning a programming language is a lot like learning another language. You need to learn new words, new punctuation, and understand how to put them together so you can communicate successfully.
In fact, every programming language has its own set of key words and characters, and its own set of rules for putting those words and characters together—the language's syntax. Learning JavaScript's syntax is like learning the vocabulary and grammar of another language. You'll need to memorize the words and rules of the language (or at least keep this book handy as a reference). When learning to speak a new language, you quickly realize that placing an accent on the wrong syllable can make a word unintelligible. Likewise, a simple typo or even a missing punctuation mark can prevent a JavaScript program from working, or trigger an error in a Web browser. You'll make plenty of mistakes as you start to learn to program—that's just the nature of programming.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
How to Add JavaScript to a Page
Web browsers are built to understand HTML and CSS and convert those languages into a visual display on the screen. The part of the Web browser that understands HTML and CSS is called the layout or rendering engine. But most browsers also have something called a JavaScript interpreter. That's the part of the browser that understands JavaScript and can execute the steps of a JavaScript program. Since the Web browser is usually expecting HTML, you must specifically tell the browser when JavaScript is coming by using the <script> tag.
The <script> tag is regular HTML. It acts like a switch that in effect says "Hey Web browser, here comes some JavaScript code; you don't know what to do with it, so hand it off to the JavaScript interpreter." When the Web browser encounters the closing </script> tag, it knows it's reached the end of the JavaScript program and can get back to its normal duties.
Much of the time, you'll add the <script> tag in the <head> portion of the Web page like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/
html4/strict.dtd">
<html>
<head>
<title>My Web Page</title>
<script type="text/javascript">

</script>
</head>
The <script> tag's type attribute indicates the format and the type of script that follows. In this case, type="text/javascript" means the script is regular text (just like HTML) and that it's written in JavaScript. Theoretically, a Web browser could handle multiple types of scripting languages, but not every browser supports other languages.
Make sure you include type="text/javascript" in the opening script tag. If you leave it out, your Web page won't validate (see the box on for more on validation).
You then add your JavaScript code between the opening and closing <script> tags:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/
html4/strict.dtd">
<html>
<head>
<title>My Web Page</title>
<script type="text/javascript">
alert('hello world!');
</script>
</head>
You'll find out what this JavaScript actually does in a moment. For now, turn your attention to the opening and closing <script> tags. To add a script to your page, start by inserting these tags. In most cases, you'll put the <script> tags in the page's <head> in order to keep your JavaScript code neatly organized in one area of the Web page.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Your First JavaScript Program
The best way to learn JavaScript programming is by actually programming. Throughout this book, you'll find hands-on tutorials that take you step-by-step through the process of creating JavaScript programs. To get started, you'll need a text editor (see for recommendations), a Web browser, and the exercise files located at www.sawmac.com/javascript (see the note on the next page for complete instructions).
The tutorials in this chapter require the example files from this book's Web site, www.sawmac.com/javascript. Click the "Download tutorials" link to download them. (The tutorial files are stored as a single Zip file.)
Windows users should download the Zip file and double-click it to open the archive. Click the Extract All Files option, and then follow the instructions of the Extraction Wizard to unzip the files and place them on your computer. Mac users, just double-click the file to decompress it. After you've downloaded and decompressed the files, you should have a folder named MM_JAVASCRIPT on your computer, containing all of the tutorial files for this book.
To get your feet wet and provide a gentle introduction to JavaScript, your first program will be very simple:
  1. .
    This file is located in the chapter01 folder in the MM_JAVASCRIPT folder you downloaded from www.sawmac.com/javascript. It's a very simple HTML page, with an external cascading style sheet to add a little visual excitement.
  2. <script type="text/javascript">
    This code is actually HTML, not JavaScript. It informs the Web browser that the stuff following this tag is JavaScript.
  3. alert('hello world');
    You've just typed your first line of JavaScript code. The JavaScript alert() function, is a command that pops open an Alert box and displays the message that appears inside the parentheses—in this case hello world. Don't worry about all of the punctuation (the parentheses, quotes, and semicolon) just yet. You'll learn what they do in the next chapter.
  4. <link href="../css/global.css" rel="stylesheet" type="text/css">
    <script type="text/javascript">
    alert('hello world');
    </script>
    </head>
    In this example, the stuff you just typed is shown in boldface. The two HTML tags are already in the file; make sure you type the code exactly where shown.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Writing Text on a Web Page
The last script popped up a dialog box in the middle of your monitor. What if you want to print a message directly onto a Web page using JavaScript? There are many ways to do so, and you'll learn some sophisticated techniques later in this book. However, you can achieve this simple goal with a built-in JavaScript command, and that's what you'll do in your second script:
  1. .
    While <script> tags usually appear in the <head> of a Web page, you can put them and JavaScript programs directly in the body of the Web page.
  2. <script type="text/javascript">
    document.write('<p>Hello world!</p>');
    </script>
    Like the alert() function, document.write() is a JavaScript command that literally writes out whatever you place between the opening and closing parentheses. In this case, the HTML <p>Hello world!</p> is added to the page: a paragraph tag and two words.
  3. .
    The page opens and the words "Hello world!" appear below the blue headline (see ).
    The tutorial files you downloaded also include the completed version of each tutorial. If you can't seem to get your JavaScript working, compare your work with the file that begins with complete_ in the same folder as the tutorial file. For example, the file complete_1.2.html contains a working version of the script you added to file 1.2.html.
The two scripts you just created may leave you feeling a little underwhelmed with JavaScript…or this book. Don't worry. It's important to start out with a full understanding of the basics. You'll be doing some very useful and complicated things using JavaScript in just a few chapters. In fact, in the remainder of this chapter you'll get a taste of some of the advanced features you'll be able to add to your Web pages after you've worked your way through the first two parts of this book.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Attaching an External JavaScript File
As discussed on , you'll usually put JavaScript code in a separate file if you want to use the same scripts on more than one Web page. You can then instruct a Web page to load that file and use the JavaScript inside it. External JavaScript files also come in handy when you're using someone else's JavaScript code. In particular, there are collections of JavaScript code called libraries, which provide useful JavaScript programming: Usually, these libraries make it easy for you to do something that's normally quite difficult to do. You'll learn more about JavaScript libraries on , and, in particular, the JavaScript library this book uses—jQuery.
Figure : Wow. This script may not be something to document.write home about—ha, ha, JavaScript humor— but it does demonstrate that you can use JavaScript to add content to a Web page, a trick that comes in handy when you want to display messages (like 'Welcome back to the site, Dave') after a Web page has downloaded.
But for now, you'll get experience attaching an external JavaScript file to a page, and writing a short program that does some amazing things:
  1. .
    This page has a basic HTML table, containing data on a handful of products (see ). HTML tables are like spreadsheets: They organize data into rows and columns. One problem with tables that contain lots of rows and columns is that it's easy to lose your place as you read across a row. One helpful visual effect many designers use is to put a background color on every other row, making it much easier to quickly scan across a row of data. To do this, you create a CSS class style that defines a background color or image, then apply that class to every other table row using HTML like this: <tr class="even">. Now, that's a lot of repetitive work, and you can ruin it just by inserting a new row in the middle of the table. Fortunately, there's a quick JavaScript solution to this common design problem.
  2. <script type="text/javascript" src="../js/jquery.js"></script>
    Figure : A plain HTML table can be hard to read if there are lots of columns, rows, and data. While scanning across a long row of data, it's easy to lose your place and view data from a different row.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Tracking Down Errors
The most frustrating moment in JavaScript programming comes when you try to view your JavaScript-powered page in a Web browser…and nothing happens. It's one of the most common experiences for programmers. Even very experienced programmers don't always get it right the first time they write a program, so figuring out what went wrong is just part of the game.
Figure : JavaScript can simplify common design tasks like changing the background color of every other table row.
Most Web browsers are set up to silently ignore JavaScript errors, so you usually won't even see a "Hey this program doesn't work!" dialog box. (Generally, that's a good thing, since you don't want a JavaScript error to interrupt the experience of viewing your Web pages.)
So how do you figure out what's gone wrong? There are many ways to track errors in a JavaScript program. You'll learn some advanced debugging techniques in , but the most basic method is to consult the Web browser. Most Web browsers keep track of JavaScript errors and record them in a separate window called a JavaScript console. When you load a Web page that contains an error, you can then view the console to get helpful information about the error, like which line of the Web page it occurred in and a description of the error.
However, not all consoles are created equal. Internet Explorer's JavaScript console is notoriously cryptic and often misleading. If you suspect errors, you'll find the most helpful JavaScript console in Firefox. Often, you can find the answer to the problem, fix the JavaScript, and then the page will work in Firefox and other browsers as well. The console helps you weed out the basic typos you make when you first start programming, like forgetting closing punctuation, or mistyping the name of a JavaScript command. But since scripts sometimes work in one browser and not another, this section shows you how to turn on the JavaScript console in all major browsers, so you can track down problems in each.
Firefox's JavaScript console is the best place to begin tracking down errors in your code. Not only does the console provide fairly clear descriptions of errors (no descriptions are ever
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: The Grammar of JavaScript
Learning a programming language is a lot like learning any new language: There are words to learn, punctuation to understand, and a new set of rules to master. And just as you need to learn the grammar of French to speak French, you must become familiar with the grammar of JavaScript to program JavaScript. This chapter covers the concepts that all JavaScript programs rely on.
If you've had any experience with JavaScript programming, many of these concepts may be old hat, so you might just skim this chapter. But if you're new to JavaScript, or you're still not sure about the fundamentals, this chapter introduces you to basic (but crucial) topics.
A JavaScript statement is a basic programming unit, usually representing a single step in a JavaScript program. Think of a statement as a sentence: Just as you string sentences together to create a paragraph (or a chapter, or a book), you combine statements to create a JavaScript program. In the last chapter you saw several examples of statements. For example:
alert('Hello World!');
This single statement opens an alert window with the message "Hello World!" in it. In many cases, a statement is a single line of code. Each statement ends with a semicolon—it's like a period at the end of a sentence. The semicolon makes it clear that the step is over and that the JavaScript interpreter should move onto the next action.
Officially, putting a semicolon at the end of a statement is optional, and some programmers leave them out to make their code shorter. Don't be one of them. Leaving off the semicolon makes reading your code more difficult and, in some cases, causes JavaScript errors. If you want to make your JavaScript code more compact so that it downloads more quickly, see .
The general process of writing a JavaScript program is to type a statement, enter a semicolon, press Return to create a new, blank line, type another statement, followed by a semicolon, and so on and so on until the program is complete.
JavaScript and Web browsers let you use various commands to make things happen in your programs and on your Web pages. For example, the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Statements
A JavaScript statement is a basic programming unit, usually representing a single step in a JavaScript program. Think of a statement as a sentence: Just as you string sentences together to create a paragraph (or a chapter, or a book), you combine statements to create a JavaScript program. In the last chapter you saw several examples of statements. For example:
alert('Hello World!');
This single statement opens an alert window with the message "Hello World!" in it. In many cases, a statement is a single line of code. Each statement ends with a semicolon—it's like a period at the end of a sentence. The semicolon makes it clear that the step is over and that the JavaScript interpreter should move onto the next action.
Officially, putting a semicolon at the end of a statement is optional, and some programmers leave them out to make their code shorter. Don't be one of them. Leaving off the semicolon makes reading your code more difficult and, in some cases, causes JavaScript errors. If you want to make your JavaScript code more compact so that it downloads more quickly, see .
The general process of writing a JavaScript program is to type a statement, enter a semicolon, press Return to create a new, blank line, type another statement, followed by a semicolon, and so on and so on until the program is complete.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Commands
JavaScript and Web browsers let you use various commands to make things happen in your programs and on your Web pages. For example, the alert() command you encountered earlier makes the Web browser open a dialog box and display a message. These commands are usually called functions or methods, and are like verbs in a sentence. They get things done.
Some commands, like alert() or document.write(), which you encountered on , are specific to Web browsers. In other words, they only work with Web pages, so you won't find them when programming in other environments that use JavaScript (like, for example, when scripting Adobe applications like Acrobat or Dreamweaver or in Flash's JavaScript-based ActionScript).
Other commands are universal to JavaScript and work anywhere JavaScript works. For example, isNaN() is a command that checks to see if a particular value is a number or not—this command comes in handy when you want to check if a visitor has correctly supplied a number for a question that requires a numerical answer (for example, "How many widgets would you like?"). You'll learn about isNaN() and how to use it in on .
JavaScript has many different commands, which you'll learn about throughout this book. One quick way to identify a command in a program is by the use of parentheses. For example, you can tell isNaN() is a command, because of the parentheses following isNaN.
In addition, JavaScript lets you create your own functions, so you can make your scripts do things beyond what the standard JavaScript commands offer. You'll learn about functions in , starting on .
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Types of Data
You deal with different types of information every day. Your name, the price of food, the address of your doctor's office, and the date of your next birthday are all information that is important to you. You make decisions about what to do and how to live your life based on the information you have. Computer programs are no different. They also rely on information to get things done. For example, to calculate the total for a shopping cart, you need to know the price and quantity of each item ordered. To customize a Web page with a visitor's name ("Welcome Back, Kotter"), you need to know his or her name.
Programming languages usually categorize information into different types, and treat each type in a different way. In JavaScript, the three most common types of data are number, string, and Boolean.
Numbers are used for counting and calculating; you can keep track of the number of days until summer vacation, or calculate the cost of buying two tickets to a movie. Numbers are very important in JavaScript programming: you can use numbers to keep track of how many times a visitor has visited a Web page, to specify the exact pixel position of an item on a Web page, or to determine how many products a visitor wants to order.
In JavaScript, a number is represented by a numeric character; 5, for example, is the number five. You can also use fractional numbers with decimals, like 5.25 or 10.3333333. JavaScript even lets you use negative numbers, like–130.
Since numbers are frequently used for calculations, your programs will often include mathematical operations. You'll learn about operators on , but just to provide an example of using JavaScript with numbers, say you wanted to print the total value of 5 plus 15 on a Web page; you could do that with this line of code:
document.write(5 + 15);
This snippet of JavaScript adds the two numbers together and prints the total (20) onto a Web page. There are many different ways to work with numbers, and you'll learn more about them starting on .
To display a name, a sentence, or any series of letters, you use strings. A string is just a series of letters and other symbols enclosed inside of quote marks. For example,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables
You can type a number, string, or Boolean value directly into your JavaScript program, but these data types work only when you already have the information you need. For example, you can make the string "Hi Bob" appear in an alert box like this:
alert('Hi Bob');
But that statement only makes sense if everyone who visits the page is named Bob. If you want to present a personalized message for different visitors, the name needs to be different depending on who is viewing the page: 'Hi Mary,' 'Hi Joseph,' 'Hi Ezra,' and so on. Fortunately, all programming languages provide something known as a variable to deal with just this kind of situation.
A variable is a way to store information so that you can later use and manipulate it. For example, imagine a JavaScript-based pinball game where the goal is to get the highest score. When a player first starts the game, her score will be zero, but as she knocks the pinball into targets, the score will get bigger. In this case, the score is a variable since it starts at 0 but changes as the game progresses—in other words, a variable holds information that can vary. See for an example of another game that uses variables.
Think of a variable as a kind of basket: you can put an item into a basket, look inside the basket, dump out the contents of a basket, or even replace what's inside the basket with something else. However, even though you might change what's inside the basket, it still remains the same basket.
Creating a variable is a two-step process that involves declaring the variable and naming it. In JavaScript to create a variable named score you would type:
var score;
The first part, var, is a JavaScript keyword that creates, or, in programming-speak, declares the variable. The second part of the statement, score, is the variable's name.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Working with Data Types and Variables
Storing a particular piece of information like a number or string in a variable is usually just a first step in a program. Most programs also manipulate data to get new results. For example, add a number to a score to increase it, multiply the number of items ordered by the cost of the item to get a grand total, or personalize a generic message by adding a name to the end: "Good to see you again, Igor." JavaScript provides various operators to modify data. An operator is simply a symbol or word that can change one or more values into something else. For example, you use the + symbol—the addition operator—to add numbers together. There are different types of operators for the different data types.
JavaScript supports basic mathematical operations such as addition, division, subtraction, and so on. shows the most basic math operators and how to use them.
Table : Basic math with JavaScript
Operator
What it does
How to use it
+
Adds two numbers
5 + 25
-
Subtracts one number from another
25 - 5
*
Multiplies two numbers
5 * 10
/
Divides one number by another
15/5
You may be used to using an x for multiplication (4 x 5, for example), but in JavaScript, you use the * symbol to multiply two numbers.
You can also use variables in mathematical operations. Since a variable is only a container for some other value like a number or string, using a variable is the same as using the contents of that variable.
var price = 10;
var itemsOrdered = 15;
var totalCost = price * itemsOrdered;
The first two lines of code create two variables (price and itemsOrdered) and store a number in each. The third line of code creates another variable (totalCost) and stores the results of multiplying the value stored in the price variable (10) and the value stored in the itemsOrdered variable. In this case, the total (150) is stored in the variable totalCost.
This sample code also demonstrates the usefulness of variables. Suppose you write a program as part of a shopping cart system for an e-commerce Web site. Throughout the program, you need to use the price of a particular product to make various calculations. You could code the actual price throughout the program (for example, say the product cost 10 dollars, so you type 10 in each place in the program that price is used). However, if the price ever changes, you'd have to locate and change each line of code that uses the price. By using a variable, on the other hand, you can set the price of the product somewhere near the beginning of the program. Then, if the price ever changes, you only need to modify the one line of code that defines the product's price to update the price throughout the program:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Tutorial: Using Variables to Create Messages
In this tutorial, you'll use variables to print (that is, write) a message onto a Web page.
To follow along with the tutorials in this chapter you need to download the tutorial files from this book's companion Web site: www.sawmac.com/missing/js. See the note on for details.
  1. This page is just a basic HTML file with a simple CSS-enhanced design. It doesn't yet have any JavaScript. You'll use variables to write a message onto a Web page.
  2. <h1>Using a Variable</h1>
    <script type="text/javascript">
    
    </script>
    This HTML should be familiar by now: it simply sets the page up for the script you're about to write.
  3. var firstName = 'Cookie';
    var lastName = 'Monster';
    You've just created your first two variables—firstName and lastName—and stored two string values into them. Next you'll add the two strings together, and print the results to the Web page.
  4. document.write('<p>');
    As you saw in , the document.write() command adds text directly to a Web page. In this case, you're using it to write HTML tags to your page. You supply the command a string—'<p>'—and it outputs that string just as if you had typed it into your HTML code. It's perfectly OK to supply HTML tags as part of the document.write() command. In this case, the JavaScript is adding the opening tag for a paragraph to hold the text you're going to print on the page.
    There are more efficient methods than document.write() to add HTML to a Web page. You'll learn about them on .
  5. document.write(firstName + ' ' + lastName);
    Here you use the values stored in the variables you created in step 3. The + operator lets you put several strings together to create one longer string, which the document.write() command then writes to the HTML of the page. In this case, the value stored in firstName—'Cookie'—is added to a space character, and then added to the value of lastName—'Monster'. The results are one string: 'Cookie Monster'.
  6. .
    The finished script should look like this:
    <script type="text/javascript">
    var firstName = 'Cookie';
    var lastName = 'Monster';
    document.write('<p>');
    document.write(firstName + ' ' + lastName);
    document.write('</p>');
    </script>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Tutorial: Asking for Information
In the last script, you saw how to create variables, but you didn't get to experience how variables can respond to the user and produce unique, customized content. In this next tutorial, you'll learn how to use the prompt() command to gather input from a user and change the display of the page based on that input.
  1. To make your programming go faster, the <script> tags have already been added to this file. You'll notice that there are two sets of <script> tags: one in the head and one in the body. The JavaScript you're about to add will do two things. First, it will open up a dialog box that asks the user to type in an answer to a question; second, in the body of the Web page, a customized message using the user's response will appear.
  2. <script type="text/javascript">
    var name = prompt('What is your name?', '');
    </script>
    The prompt() command produces a dialog box similar to the alert() command. However, instead of just displaying a message, the prompt() command can also retrieve an answer (see ). In addition, to use the prompt() command, you supply two strings separated by a comma between the parentheses. shows what happens to those two strings: the first string appears as the dialog's question ("What is your name?" in this example).
    The second string appears in the field the visitor types into. This example uses what's called an empty string, which is just two single quote marks ('') and results in a blank text field. However, you can supply a useful instruction like "Please type both your first and last names" for the second string, and it will appear in the field. Unfortunately, a visitor will need to first delete that text from the text field before entering his own information.
    The prompt() command returns a string containing whatever the visitor typed into the dialog box. In this line of JavaScript code, that result is stored into a new variable named
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Arrays
Simple variables, like the ones you learned about in the previous section, only hold one piece of information, such as a number or a string value. They're perfect when you only need to keep track of a single thing like a score, an age, or a total cost. However, if you need to keep track of a bunch of related items—like the names of all of the days in a week, or a list of all of the images on a Web page—simple variables aren't very convenient.
Figure : The power of variables: this page customizes its message based on a visitor's response.
For example, say you've created a JavaScript shopping cart system that tracks items a visitor intends to buy. If you wanted to keep track of all of the items the visitor adds to her cart using simple variables you'd have to write code like this:
var item1 = 'Xbox 360';
var item2 = 'Tennis shoes';
var item3 = 'Gift certificate';
But what if they wanted to add more items than that? You'd have to create more variables—item4, item5, and so on. And, because you don't know how many items the visitor might want to buy, you really don't know how many variables you'll have to create.
Fortunately, JavaScript provides a better method of tracking a list of items, called an array. An array is a way of storing more than one value in a single place. Think of an array like a shopping list. When you need to go to the grocery store, you sit down and write a list of items to buy. If you just went shopping a few days earlier, the list might only contain a few items; but if your cupboard is bare, your shopping list might be quite long. Regardless of how many items on the list, though, there's still just a single list.
Without an array, you have to create a new variable for each item in the list. Imagine, for example, that you couldn't make a list of groceries on a single sheet of paper, but had to carry around individual slips of paper—one for each item that you're shopping for. If you wanted to add another item to buy, you'd need a new slip of paper; then you'd need to keep track of each slip as you shopped (see ). That's how simple variables work. But with an array you can create a single list of items, and even add, remove, or change items at anytime.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Tutorial: Writing to a Web Page Using Arrays
You'll use arrays in many of the scripts in this book, but to get a quick taste of creating and using arrays, try this short tutorial.
See the note on for information on how to download the tutorial files.
  1. .
    You'll start by simply creating an array containing four strings. As with the previous tutorial, this file already contains <script> tags in both the head and body regions.
  2. <script type="text/javascript">
    var authors = [ 'Ernest Hemingway',
                    'Charlotte Bronte',
                    'Dante Alighieri',
                    'Emily Dickinson'
                  ];
    </script>
    This code comprises a single JavaScript statement, but it's broken over five lines. To create it, type the first line—var authors = [ 'Ernest Hemingway', —hit Return, then press the Space bar until you line up under the ' (about 16 spaces), and then type 'Charlotte Bronte',.
    Most HTML editors use a monospaced font like Courier or Courier New for your HTML and JavaScript code. In a monospaced font, each character is the same width as every other character, so it's easy to line up columns (like all the author names in this example). If your text editor doesn't use Courier or something similar, you may not be able to line up the names perfectly.
    As mentioned on , when you create an array with lots of elements, you can make your code easier to read if you break it over several lines. You can tell it's a single statement since there's no semicolon until the end of line 5.
    This line of code creates an array named authors and stores the names of 4 authors (4 string values) into the array. Next, you'll access an element of the array.
  3. <script type="text/javascript">
    document.write('<p>The first author is <strong>');
    document.write(authors[0] + '</strong></p>');
    </script>
    The first line starts a new paragraph with some text and an opening <strong> tag—just plain HTML. The next line prints the value stored in the first item of the authors array and prints the closing </strong> and </p> tags to create a complete HTML paragraph. To access the first item in an array, you use a 0 as the index—authors[0]—instead of 1.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Comments
There are times when you're in the midst of programming and you feel like you understand everything that's going on in your program. Every line of code makes sense, and better yet, it works! But a month or two later, when your boss or a client asks you to make a change or add a new feature to that cool script you wrote, you might find yourself scratching your head the moment you look at your once-familiar JavaScript: what's that variable for? Why'd I program it like that? What's going on in this section of the program?
It's easy to forget how a program works and why you wrote your code the way you did. Fortunately, most programming languages provide a way for programmers to leave notes for themselves or other programmers who might look through their code. JavaScript lets you leave comments throughout your code. If you've used HTML or CSS comments, these should feel familiar. A comment is simply a line or more worth of notes: the JavaScript interpreter ignores them, but they can provide valuable information on how your program works.
The syntax for JavaScript comments is the same as for CSS. To create a single line comment, precede the comment with double forward slashes:
// this is a comment
You can also add a comment after a JavaScript statement:
var price = 10; // set the initial cost of the widget
The JavaScript interpreter executes everything on this line until it reaches the //, and then it skips to the beginning of the next line.
You can also add several lines worth of comments by beginning the comments with /* and ending them with */. The JavaScript interpreter ignores all of the text between these two sets of symbols. For example, say you want to give a description of how a program works at the beginning of your code. You can do that like this:
/*
   JavaScript Slideshow:
   This program automates the display of
   images in a pop-up window.
*/
You don't need to leave the /* and */ on their own lines, either. In fact, you can create a single line JavaScript comment with them:
/* this is a single line comment */
In general, if you want to just write a short, one-line comment, use //. For several lines of comments, use the /* and */ combination.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Adding Logic and Control to Your Programs
So far you've learned about some of JavaScript's basic building blocks. But simply creating a variable and storing a string or number in it doesn't accomplish much. And building an array with a long list of items won't be very useful unless there's an easy way to work your way through the items in the array. In this chapter, you'll learn how to make your programs react intelligently and work more efficiently by using conditional statements, loops, and functions.
Our lives are filled with choices: "What should I wear today?", "What should I eat for lunch?", "What should I do Friday night?", and so on. Many choices you make depend on other circumstances. For example, say you decide you want to go to the movies on Friday night. You'll probably ask yourself a bunch of questions like "Are there any good movies out?", "Is there a movie playing at the right time?", "Do I have enough money to go to the movies (and buy a $17 bag of popcorn)?"
Suppose there is a movie that's playing at just the time you want to go. You then ask yourself a simple question: "Do I have enough money?" If the answer is yes, you'll head out to the movie. If the answer is no, you won't go. But on another Friday, you do have enough money, so you go to the movies. This scenario is just a simple example of how the circumstances around us affect the decisions we make.
JavaScript has the same kind of decision-making feature called conditional statements. At its most basic, a conditional statement is a simple yes or no question. If the answer to the question is yes, your program does one thing; if the answer is no, it does something else. Conditional statements are one of the most important programming concepts: they let your programs react to different situations and behave intelligently. You'll use them countless times in your programming, but just to get a clear picture of their usefulness here are a few examples of how they can come in handy:
  • . When you want to make sure someone filled out all of the required fields in a form ("Name," "Address," "E-mail", and so on), you'll use conditional statements. For example, if the Name field is empty, don't submit the form.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Making Programs React Intelligently
Our lives are filled with choices: "What should I wear today?", "What should I eat for lunch?", "What should I do Friday night?", and so on. Many choices you make depend on other circumstances. For example, say you decide you want to go to the movies on Friday night. You'll probably ask yourself a bunch of questions like "Are there any good movies out?", "Is there a movie playing at the right time?", "Do I have enough money to go to the movies (and buy a $17 bag of popcorn)?"
Suppose there is a movie that's playing at just the time you want to go. You then ask yourself a simple question: "Do I have enough money?" If the answer is yes, you'll head out to the movie. If the answer is no, you won't go. But on another Friday, you do have enough money, so you go to the movies. This scenario is just a simple example of how the circumstances around us affect the decisions we make.
JavaScript has the same kind of decision-making feature called conditional statements. At its most basic, a conditional statement is a simple yes or no question. If the answer to the question is yes, your program does one thing; if the answer is no, it does something else. Conditional statements are one of the most important programming concepts: they let your programs react to different situations and behave intelligently. You'll use them countless times in your programming, but just to get a clear picture of their usefulness here are a few examples of how they can come in handy:
  • . When you want to make sure someone filled out all of the required fields in a form ("Name," "Address," "E-mail", and so on), you'll use conditional statements. For example, if the Name field is empty, don't submit the form.
  • . If you add the ability to drag elements around your Web page, you might want to check where the visitor drops the element on the page. For example, if he drops a picture onto an image of a trash can, you make the photo disappear from the page.
  • . If you pop-up a window to ask a visitor a question like "Would you like to answer a few questions about how great this Web site is?", you'll want your script to react differently depending on how the visitor answers the question.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Tutorial: Using Conditional Statements
Conditional statements will become part of your day-to-day JavaScript toolkit. In this tutorial, you'll try out conditional statements to control how a script runs.
See the note on for information on how to download the tutorial files.
  1. .
    You'll start by simply prompting the visitor for a number. This file already contains <script> tags in both the head and body regions.
  2. <script type="text/javascript">
    var luckyNumber = prompt('What is your lucky number?','');
    </script>
    This line of code opens a JavaScript prompt dialog box, asks a question, and stores whatever the visitor typed into the luckyNumber variable. Next, you'll add a conditional statement to check what the visitor typed into the prompt dialog box.
  3. <script type="text/javascript">
    if (luckyNumber == 7 ) {
    </script>
    Here's the beginning of the conditional statement; it simply checks to see if the visitor typed 7.
  4. <script type="text/javascript">
    if (luckyNumber == 7 ) {
    
    }
    </script>
    The closing brace ends the conditional statement. Any JavaScript you add between the two braces will only run if the condition is true.
    As mentioned on , it's a good idea to add the closing brace before writing the code that runs as part of the conditional statement.
  5. document.write("Hey, 7 is my lucky number too!");
    The two spaces before the code indent the line so you can easily see that this code is part of the conditional statement. The actual JavaScript here should feel familiar by now—it simply writes a message to the page.
  6. .
    You should see the message "Hey, that's my lucky number too!" below the headline when the page loads. If you don't, go over your code and make sure you typed it correctly (see for tips on dealing with a broken script). Reload the page, but this time type a different number. This time, nothing appears underneath the headline. You'll add an else clause to print another message.
  7. <script type="text/javascript">
    if (luckyNumber == 7 ) {
     document.write("Hey, 7 is my lucky number too!");
    } else {
     document.write("The number " + luckyNumber + " is lucky for you!");
    }
    </script>
    The else clause provides a backup message, so that if the visitor doesn't type
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Handling Repetitive Tasks with Loops
Sometimes a script needs to repeat the same series of steps over and over again. For example, say you have a Web form with 30 text fields. When the user submits the form, you want to make sure that none of the fields are empty. In other words, you need to perform the same set of actions—check to see if a form field is empty—30 times. Since computers are good at performing repetitive tasks, it makes sense that JavaScript includes the tools to quickly do the same thing repeatedly.
In programming-speak, performing the same task over and over is called a loop, and because loops are so common in programming JavaScript offers several different types. All do the same thing, just in slightly different ways.
A while loop repeats a chunk of code as long as a particular condition is true; in other words, while the condition is true. The basic structure of a while loop is this:
while (condition) {
 // javascript to repeat
}
The first line introduces the while statement. As with a conditional statement, you place a condition between the set of parentheses that follow the keyword while. The condition is any test you'd use in a conditional statement, such as x > 10 or answer == 'yes'. And just like a conditional statement, the JavaScript interpreter runs all of the code that appears between the opening and closing braces if the condition is true.
However, unlike a conditional statement, when the JavaScript interpreter reaches the closing brace of a while statement, instead of continuing to the next line of the program, it jumps back to the top of the while statement and tests the condition a second time. If the condition is again true, the interpreter runs JavaScript between the braces a second time. This process continues until the condition is no longer true; then the program continues to the next statement following the loop (see ).
Figure : A while loop runs the JavaScript code between curly braces as long as the test condition (x < 10 in this case) is true.
Say you want to print the numbers 1 to 5 on a page. One possible way to do that is like this:
document.write('Number 1 <br>');
document.write('Number 2 <br>');
document.write('Number 3 <br>');
document.write('Number 4 <br>');
document.write('Number 5 <br>');
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Functions: Turn Useful Code Into Reusable Commands
Imagine that at work you've just gotten a new assistant to help you with your every task (time to file this book under "fantasy fiction"). Suppose you got hungry for a piece of pizza, but since the assistant was new to the building and the area, you had to give him detailed directions: "Go out this door, turn right, go to the elevator, take the elevator to the first floor, walk out of the building…" and so on. The assistant follows your directions and brings you a slice. A couple hours later you're hungry again, and you want more pizza. Now, you don't have to go through the whole set of directions again— "Go out this door, turn right, go to the elevator…". By this time, your assistant knows where the pizza joint is, so you just say, "Get me a slice of pizza," and he goes to the pizza place and returns with a slice.
In other words, you only need to provide detailed directions a single time; your assistant memorizes those steps and with the simple phrase "Get me a slice" he instantly leaves and reappears a little while later with a piece of pizza. JavaScript has an equivalent mechanism called a function. A function is a series of programming steps that you set up at the beginning of your script—the equivalent of providing detailed directions to your assistant. Those steps aren't actually run when you create the function; instead, they're stored in the Web browser's memory, where you can call upon them whenever you need those steps performed.
Functions are invaluable for efficiently performing multiple programming steps repeatedly: for example, say you create a photo gallery Web page filled with 50 small thumbnail images. When someone clicks one of the small photos, you might want the page to dim, a caption to appear, and a larger version of that image to fill the screen (you'll learn to do just that on ). Each time someone clicks an image, the process repeats, so on a Web page with 50 small photos, your script might have to do the same series of steps 50 times. Fortunately, you don't have to write the same code 50 times to make this photo gallery work. Instead, you can write a function with all the necessary steps, and then, with each click of the thumbnail, you run the function. You write the code once, but run it any time you like.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Tutorial: A Simple Quiz
Now it's time to bring together the lessons from this chapter and create a complete program. In this tutorial, you'll create a simple quiz system for asking questions and evaluating the quiz-taker's performance. First, this section will look at a couple of ways you could solve this problem, and discuss efficient techniques for programming.
As always, the first step is to figure out what exactly the program should do. There are a few things you want the program to accomplish:
  • . If you're going to quiz people, you need a way to ask them questions. At this point, you know one simple way to get feedback on a Web page: the prompt() command. In addition, you'll need a list of questions; since arrays are good for storing lists of information, you'll use an array to store your quiz questions.
  • . First, you need to determine if the quiz-taker gave the right answer: a conditional statement can take care of that. Then, to let the quiz taker know if she's right or wrong, you can use the alert()command.
  • . You need a way to track how well the quiz-taker's doing—a variable that keeps track of the number of correct responses will work. Then, to announce the final results of the quiz, you can either use the alert() command or the document.write() method.
There are many ways to solve this problem. Some beginning programmers might take a blunt-force approach and repeat the same code to ask each question. For example, the JavaScript to ask the first two questions in the quiz might look like this:
var answer1=prompt('How many moons does Earth have?','');
if (answer1 == 1 ) {
 alert('Correct!');
} else {
 alert('Sorry. The correct answer is 1');
}
var answer2=prompt('How many moons does Saturn have?','');
if (answer2 == 31) {
 alert('Correct!');
} else {
 alert('Sorry. The correct answer is 31');
}
This kind of approach seems logical, since the goal of the program is to ask one question after another. However, it's not an efficient way to program. Whenever you see the same steps written multiple times in a program, it's time to consider using a loop or a function instead. We'll create a program that does both: uses a loop to go through each question in the quiz, and a function that performs the question asking tasks:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Working with Words, Numbers, and Dates
Storing information in a variable or an array is just the first step in effectively using data in your programs. As you read in the last chapter, you can use data to make decisions in a program ("Is the score 0?"). You'll also frequently manipulate data by either searching through it (trying to find a particular word in a sentence, for example), manipulating it (rounding a number to a nearest integer), or reformatting it to display properly (formatting a number like 430 to appear in the proper monetary format, like $430.00).
This chapter will show you how to accomplish common tasks when working with strings and numbers. In addition, it'll introduce the JavaScript Date object, which lets you determine the current date and time on a visitor's computer.
So far in this book, you've learned that you can write something to a Web page with the document.write() command, and to determine how many items are in an array, you type the name of the array followed by a period and the word "length," like so: days.length. You're probably wondering what those periods are about. You've made it through three chapters without learning the particulars of this feature of JavaScript syntax, and it's time to address them.
You can conceptualize many of the elements of the JavaScript language, as well as elements of a Web page, as objects. The real world, of course, is filled with objects too, such as a dog or a car. Most objects are made up of different parts: a dog has a tail, a head, and four legs; a car has doors, wheels, headlights, a horn, and so on. An object might also do something—a car can transport passengers, a dog can bark. In fact, even a part of an object can do something: for example, a tail can wag, and a horn can honk. illustrates one way to show the relationships between objects, their parts, and actions.
Table : A simplified view of the world
Object
Parts
Actions
dog
bark
tail
wag