A Balanced Introduction to Computer Science and Programming

David Reed
Creighton University

Copyright © 2004 by Prentice Hall



Chapter 4: Dynamic Web Pages via JavaScript


As you learned in Chapter 2 and Chapter 3, the World Wide Web is a vast, interconnected network of documents that effectively integrates text and media such as images, movies, and sounds. The HyperText Markup Language (HTML) consists of tags that identify the contents of a page and provide formatting information for the Web browser. Using HTML tags, it is possible to develop attractive, information-rich pages for the Web. However, HTML alone can only produce static pages, i.e., pages that always look and behave the same each time they are loaded into the browser.

In 1995, Netscape Communications Corporation developed a simple programming language that could be used to augment Web pages and make them dynamic. This language would eventually be known as JavaScript, acknowledging its close ties to the general purpose programming language Java. Unlike Java, however, JavaScript is a relatively simple language with features designed for easy integration into Web pages. Code written in JavaScript can be embedded in a Web page and automatically executed by the browser when the page is loaded. Utilizing the expressive power of JavaScript, Web pages can be made to interact with the user and vary their content based on a variety of events.

In this chapter, you will begin augmenting your own Web pages with JavaScript, focusing first on simple techniques for interacting with the user.


Dynamic Web pages

If you have spent any time surfing the Web, you have no doubt encountered pages that change content and interact with you. At commercial sites, banner ads may cycle as you view the site, or may react when you place the mouse over them. Search engines prompt you for topics and then retrieve information based on your response. These are examples of dynamic pages since their behavior changes each time they are loaded or as events occur. Throughout this text, you will learn to develop dynamic pages with similar capabilities using JavaScript. For now, you will start with simple Web pages that are able to interact with the user and display dynamic content based on that interaction.

For example, suppose you wanted to create a Web page that customized itself by asking the user their name and then incorporating that name within the text of the page. The following Web page accomplishes this task by utilizing simple features of JavaScript, which will be explained below.

<html> <!-- greet.html Dave Reed --> <!-- Web page that displays a personalized greeting. --> <!------------------------------------------------------> <head> <title> Greetings </title> </head> <body> <script type="text/javascript"> firstName = prompt("Please enter your name", ""); document.write("Hello " + firstName + ", welcome to my Web page."); </script> <p> Whatever else you want to appear in your Web page... </p> </body> </html>

JavaScript statements are commands that tell the browser to perform specific actions, such as prompting the user for their name or displaying a message within the page. The simplest way to add dynamic content to a Web page is to directly embed JavaScript statements within the page using SCRIPT tags. Statements embedded between the tags <script language="JavaScript"> and </script> are recognized by the Web browser as JavaScript code, and are automatically executed (i.e., the actions specified by the statements are carried out in order) when the page is loaded. In this example, there are two JavaScript statements within the SCRIPT tags, which combine to produce the interactive behavior described above.


Classic errors to avoid...

You may note that each statement in the above example ends with a semi-colon. Technically, every JavaScript statement is required to end with a semi-colon, although browsers tend to be forgiving if you occasionally omit them. Since there are times where a missing semi-colon can cause confusion or even an error, you should be careful to always include them in your statements.



EXERCISE 4.1:   Cut-and-paste the greet.html text into a new Web page and verify that it behaves as described. In particular, what is displayed if the user clicks OK without entering a value in the input area?


Since the output produced by a write statement is embedded in the Web page and displayed by the browser just like any other text, that output can be formatted using HTML tags. For example, assuming the user entered "Dave" for their name, the write statement

document.write("Hello <i>" + firstName + "</i>, welcome to my Web page.");

would write the text

Hello <i>Dave</i>, welcome to my Web page. into the HTML document, which is then displayed by the browser as
    Hello Dave, welcome to my Web page.

Note that within the output message, the <i></i> tags appear inside the quotes as they are part of the text being written to the Web page. In contrast, the variable firstNameappears outside of quotes, ensuring that the browser will recognize it as a variable and substitute the corresponding value. If you mistakenly placed a variable inside quotes in an output message, the variable name would be displayed as opposed to its value.


EXERCISE 4.2:   Modify your greet.html page so that the the user's name appears in bold, and the output is broken across two lines. For example:

Hello Dave,
welcome to my Web page.



Classic errors to avoid...

As you completed the previous exercise, adding new JavaScript code to the greet.html page, it is very likely that at some point you made a mistake. You might have forgotten the closing quotes on the message or misspelled document.write. Such errors in the format of statements, be it HTML or JavaScript, are known as syntax errors. For the most part, HTML syntax errors are easy to spot and correct: usually the browser just ignores malformed tags and continues on with the page. In contrast, syntax errors in JavaScript code can sometimes be difficult to identify.

Fortunately, modern Web-browsers attempt to assist you in identifying and correcting JavaScript syntax errors. Using Internet Explorer, you can set preferences so that a JavaScript syntax error will cause a window to appear with an error message identifying the cause of the error. Under the Tools menu, select Internet Options and click on the Advanced tab. Then, make sure the boxes labeled "Display a notification about every script error" and "Disable script debugging" are checked.

Using a Netscape browser, an error message may not automatically appear, however, the user can open the JavaScript Console to see detailed error messages. The Netscape JavaScript Console can be opened from the Tools menu, or by typing "javascript:" in the Address box.


Variables names

As the greet.html page demonstrates, a variable can be used to represent a value, such as a name entered by the user. For the most part, you can choose any name you wish to represent a value. Technically, a variable name can be any sequence of letters, digits, and underscores that starts with a letter. For example, all of the following are valid JavaScript variable names:

tempInFahr SUM current_age Sum2Date x

Note that JavaScript is case-sensitive, meaning that capitalization does matter. Consequently, names such as sum, Sum, and SUM each represent different variables. Furthermore, there are some words that are reserved by JavaScript and Web browsers for their own use, and so should not be used for variables. Relax: this table seems big, but most of these words are technical and you would never attempt to use them as variables anyway!

Reserved words that shouldn't be used as variables
alert Element JavaArray onload status Anchor else JavaClass onunload String Area escape JavaObject open submit Array eval JavaPackage opener sun assign false length Option taint blur FileUpload Link Packages Text Boolean focus Location parent Textarea Button for location parseFloat this break Form Math parseInt top CheckBox Frame MimeType Password toString class frames name Plugin true clearTimeout function navigate prompt typeof close Function Navigator prototype unescape closed getClass netscape Radio untaint confirm Hidden new ref valueof continue History Number Reset void Date if null return while defaultStatus Image Object scroll window delete in onblur Select Window document isNaN onerror self with Document java onfocus setTimeout


EXERCISE 4.3:   Each of the following is invalid as a JavaScript variable name. Explain why.

2hotforU salary$ two words "sum_to_date" name



EXERCISE 4.4:   Modify your greet.html page so that it prompts the user twice, once for their first name and again for their last name. You will need to use a second variable to store the last name: choose a variable name that suggests its purpose, such as lastName or surname. Once both names have been read in, the page should display the following message (with the appropriate names substituted, of course).

Hello Dave Reed,
or may I just call you Dave?



Classic errors to avoid...

The case-sensitivity of variables in JavaScript can lead to subtle errors. For example, suppose you assigned a value to a variable named firstName, then later mistakenly assigned a new value under the name firstname.

firstName = prompt("Enter your name", ""); // other code here firstname = prompt("Enter another name", "");

Despite the apparent similarity of these two variable names, the browser would treat them as being independent. The second assignment would be assign a value to firstname, leaving firstName unchanged. In addition to the confusion caused by mistyped variable names, an error will occur if an attempt is made to access the value of the mistyped variable before assigning it a value. For example:

lastName = prompt("Enter your last name", ""); // other code here document.write(lastname);

An error would occur when this code is executed, since the variable lastname has not had a value assigned to it (despite the fact that lastName has). The error message would identify the write statement as the source of the error and state that "lastname is not defined."


Variables and memory cells

In the abstract, a variable is a name that represents some value. In practice, this is accomplished by associating with each variable a piece of memory, known as a memory cell. Each memory cell inside the computer stores the value of its corresponding variable.

In JavaScript, a value is assigned to a variable (and thus stored in its associated memory cell) via an assignment statement (using '='). For example, in the greet.htmlpage above, the variable firstName is assigned the value obtained by the prompt function, as entered by the user. Values can be directly assigned to variables as well, such as assigning the variable color to have the value "green".

firstName = prompt("Please enter your name", ""); color = "green";

Assignments to variables can be visualized by drawing a box to represent the memory cell, labeled by the variable name. When an assignment is made, the assigned value is stored in the memory cell.

 
"Dave"
 
      
 
"green"
 
firstName
color

Once you have assigned a value to a particular variable, any reference to the variable name evaluates to the value stored in its associated memory cell. That is, the value stored in the memory cell is substituted for the variable name. For example, after assigning color to have the value "green", the following two write statements are equivalent:

document.write("My favorite color is green."); document.write("My favorite color is " + color + ".");

It is even possible to assign a value to a variable more than once. Each new assignment overwrites the old contents of the memory cell with the new value being assigned. For example, the JavaScript code in the Web page below prompts the user for their favorite food, stores their response in the variable food, and then displays a message containing that food. It then prompts the user for their least favorite food and similarly displays it. Since the favorite food is no longer needed, the same variable food can be reused, overwriting the old value.

<html> <!-- food.html Dave Reed --> <!-- Web page that prompts and displays food preferences. --> <!----------------------------------------------------------> <head> <title> Who’s Hungry? </title> </head> <body> <script type="text/javascript"> food = prompt("What is your favorite food?", "chocolate"); document.write("Your favorite food is " + food + "<br />"); food = prompt("What is your least favorite food?", "brussels sprouts"); document.write("Your least favorite food is " + food + "<br />"); </script> </body> </html>


EXERCISE 4.5:   Cut-and-paste the food.html text into a new Web page and verify that it behaves as described. In particular, what is displayed if the user clicks OK without entering values at the prompts?



EXERCISE 4.6:   What would happen if the second and third statements in the above code were swapped? That is, what if the two prompts were executed before the two write statements? Modify the code in food.html to verify your prediction.


Designer secrets...

You may have noticed that the JavaScript code you have written so far tends to follow a certain pattern. This should not be surprising since the tasks you have performed in this chapter have been similar in nature. In the case of greet.html, the page needed to prompt the user for their name(s) and incorporate the name(s) in the text of the page. Similarly, the food.html page needed to prompt the user for favorite and least favorite foods and incorporate them in the text of the page.

Whenever you are writing a page that needs to get information from the user and incorporate that information in the page, you will need a sequence of statements that prompt the user for input values and store them in variables, followed by one or more write statements that display messages involving the inputs. Thus, the following general pattern holds:

<script type="text/javascript"> input1 = prompt("PROMPT MESSAGE", ""); input2 = prompt("PROMPT MESSAGE", ""); . . . inputN = prompt("PROMPT MESSAGE", ""); document.write("MESSAGE INVOLVING input1, …, inputN"); </script>


As another example, consider the following Web page, which utilizes JavaScript code to display a verse of the children's song "Old MacDonald had a Farm." The user is prompted for the name of an animal and the sound it makes, and those words are then incorporated into the write statements that display the verse.

<html> <!-- oldmac.html Dave Reed --> <!-- Web page that displays a verse of Old MacDonald. --> <!------------------------------------------------------> <head> <title> Old MacDonald </title> </head> <body> <script type="text/javascript"> animal = prompt("Enter a kind of animal:", "cow"); sound = prompt("What kind of sound does it make?", "moo"); document.write("<p>Old MacDonald had a farm, E-I-E-I-O.<br />"); document.write("And on that farm he had a " + animal + ", E-I-E-I-O.<br />"); document.write("With a " + sound + "-" + sound + " here, and a " + sound + "-" + sound + " there,<br />"); document.write(" here a " + sound + ", there a " + sound + ", everywhere a " + sound + "-" + sound + ".<br />"); document.write("Old MacDonald had a farm, E-I-E-I-O.</p>"); </script> </body> </html>

Note that this page again follows the general pattern of prompting the user for inputs (here, the name of an animal and the sound it makes) and then displays messages that include those inputs. In this case, the calls to prompt utilize default values, so that if the user clicks OK in the dialog box without entering anything, then "cow" and "moo" will be used. Also note that two of the write statements span multiple lines. This is perfectly legal as long as you don't split a string. That is, the opening and closing quotes for a string must appear on the same line.


EXERCISE 4.7:   Cut-and-paste the oldmac.html text into a new Web page and verify that it behaves as described.


EXERCISE 4.8:   Modify your oldmac.html page so that it displays three verses of the song, prompting the user for an animal and sound between each verse. Specifically, cut-and-paste three copies of the code for reading in the inputs and displaying the verse (within the same pair of SCRIPT tags). The same variables can be used for each verse, since each assignment to a variable overwrites the previous value. The calls to prompt should utilize different default values for each verse, however.


In addition to storing values read in from the user, a common use of variables is to store values that are referred to over and over. If a variable is used repeatedly in a section of code, changing a single assignment to that variable can automatically affect the entire page. For example, you may note that the refrain "E-I-E-I-O" appears several times in the Old MacDonald verse. Depending on the source, this refrain may be spelled differently, such as "Eeyigh-Eeyigh-Oh". If this was something you might want to change, you could use a variable to store the desired spelling and then use that variable in the write statements. In effect, all of the verses could be changed simply by changing the single assignment to the variable.


EXERCISE 4.9:   Modify your oldmac.html page so that it stores the refrain in a variable and then uses that variable in the write statements. That is, add the assignment refrain = "E-I-E-I-O"; at the very top of the JavaScript code (just after the opening SCRIPT tag) and modify the write statements as in the following: document.write("<p>Old MacDonald had a farm, " + refrain + ".<br />"); Since the spelling assigned to the refrain variable is the same as before, the behavior of the page should not change.



EXERCISE 4.10:   Modify your oldmac.html page so that the alternate spelling "Eeyigh-Eeyigh-Oh" is used in all of the verses. Hint: due to the use of the variable refrain, this modification should only require a minimal change to your code.



Classic errors to avoid...

When writing JavaScript statements involving strings and variables, there are two types of errors that commonly occur. Learning to recognize and understand each type of error can save you considerable amounts of time and frustration.

Error: unterminated string literal
This error message appears when the browser encounters the beginning of a string but fails to find the closing quote on the same line. A write statement can be broken across multiple lines using '+', but each piece of the message (i.e., each individual string) must be complete on a line. For example, document.write("This example is illegal since the string is broken across lines"); document.write("This example is ok, since the message " + "is broken into two distinct strings");
Error: missing ) after argument list
This error message appears when the pieces of a message are not connected correctly (and thus the browser is confused and looking to end the write statement). Most often, the '+' is missing between individual pieces. For example, document.write("The value of x is " x); // error, should be '+' in between document.write("The value of x is " + x); // OK


Interactive pages

A Mad Lib (Putnam Publishing Group) is a popular party activity where a potentially humorous story is written down, with blanks in the place of some of the key words. Before reading the story, the storyteller asks others present to fill in those blanks. Those selecting the words are only told the type of word required, and have no other knowledge of the story. This lack of context in selecting words can result in an entertaining story when the words are plugged in to the appropriate places. For example, consider the following beginning to a story.

It was a  adjective  kind of day when  person's name  walked out into the street. The sky was a deep  color , and  same name  was walking his new pet  animal  ...

Making the following substitutions:

adjective = smarmy
person's name = Chris
color = mauve
animal = gnu

the story would read:

It was a smarmy kind of day when Chris walked out into the street. The sky was a deep mauve, and Chris was walking his new pet gnu ...

Now that you know how to create interactive Web pages using HTML and JavaScript, you can write a simple page that generates Mad Libs.

EXERCISE 4.11:    Create a Web page named madlib.html that serves as an interactive Mad Lib program. Your page should contain JavaScript code that prompts the user for words to fill in the blanks in a story, and then stores those words in variables. After having read in all of the words, your code should then display the story in the Web page, using the values of the variables where appropriate.

The content of the story can be anything that you like -- be creative! Your story must meet the following conditions, however.



Chapter Summary


Supplemental (optional) material and exercises Solutions to odd numbered exercises