CSC 107      Spring 2002

Lesson 2: Dynamic Web Pages via JavaScript

As you learned in Lesson 1, 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 an HTML document 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 lesson, 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 such as Google and Ask Jeeves 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. As this course progresses, 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 HTML document accomplishes this task by utilizing simple features of JavaScript, which will be explained below.

<html> <!-- Dave Reed greet.html 1/20/02 --> <!-- --> <!-- Web page that displays a personalized greeting. --> <!------------------------------------------------------> <head> <title> Greetings </title> </head> <body> <script language="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... </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 HTML document 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.

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 2.1:   Cut-and-paste the greet.html text into a new HTML document 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 HTML document 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 as
    Hello Dave, welcome to my Web page.

When this text is displayed in the Web browser, the <i></i> tags cause the name Dave to appear in italics. 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 HTML document. In contrast, the variable firstName appears 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 2.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.

What to do when things go wrong...

As you completed the previous exercise, adding new JavaScript code to the greet.html document, 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 Netscape, a short error message will appear in the status bar (the bottom panel) on the browser window, although that message may be short-lived and easy to overlook. However, if you enter "javascript:" in the Address box, the JavaScript Console will open in a separate browser window. The JavaScript Console will identify the line in the HTML document where the syntax error is believed to occur along with a descriptive error message. Usually, this error message will be very helpful in fixing the underlying error. Using Internet Explorer, syntax errors are more obvious since a window automatically pops up identifying the error. Unfortunately, the error messages provided by IE are more primitive than Netscape, providing only the line number where the error occurred.

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 cannot 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 2.3:   Each of the following is invalid as a JavaScript variable name. Explain why.

2hotforU salary$ two words "sum_to_date" name

EXERCISE 2.4:   Modify your greet.html document 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?

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.html page 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 (overwriting any previous value that might have been stored there).


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 HTML document 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 1/20/02 --> <!-- --> <!-- Web page that prompts and displays food preferences. --> <!-----------------------------------------------------------> <head> <title> Who’s Hungry? </title> </head> <body> <script language="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 2.5:   Cut-and-paste the food.html text into a new HTML document and verify that it behaves as described. In particular, what is displayed if the user clicks OK without entering values at the prompts?

EXERCISE 2.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? Cut-and-paste the above JavaScript code into a new HTML document named food.html to verify your prediction.

As another example, consider the following HTML document, 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 1/20/02 --> <!-- --> <!-- Web page that displays a verse of Old MacDonald. --> <!-------------------------------------------------------------> <head> <title> Old MacDonald </title> </head> <body> <script language="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.<br>"); </script> </body> </html

Note that 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 2.7:   Cut-and-paste the oldmac.html text into a new HTML document and verify that it behaves as described.

EXERCISE 2.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 2.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 2.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.

Interactive pages

A Mad Lib 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 2.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.

Lesson Summary

Additional (optional) exercises Solutions to odd numbered exercises