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.
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.
Whatever else you want to appear in your Web page... |
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.
This type of statement is known as an assignment statement since its purpose is to assign a name to particular value so that it can be referred to throughout the page. In programming terminology, a variable is a name that is given to a value so that it can be remembered and referred to later. In this example, the user is prompted to enter their name and that name is assigned to the variable firstName, for later reference.
The user is prompted for their name via a call to the predefined prompt function. In simple terms, a function is a collection of JavaScript statements that carry out a specific task, and a call to that function causes those statements to be executed. (Formal definitions of function and function call will be provided in Chapter 5.) Here, the call to prompt causes a dialog box, a separate window where a use can enter values, to appear:
The white rectangle in the dialog box is the input area where the user can enter text, then click on the OK button when input is complete. Note that the prompt message that appears within the dialog box, Please enter your name, is the text listed first inside the call to prompt. The prompt message can be any sequence of characters enclosed in quotes, known as a string in JavaScript. Note also that the call to prompt has a second string value listed, which is the default value to be initially displayed in the input box. In this case, the default value is the empty string "", so the input area initially appears empty.
In general, the user can be prompted for any value and that value remembered using a JavaScript assignment statement of the form:
This type of JavaScript statement is known as a write statement since it utilizes the predefined document.write function to display the message in the Web page. The message displayed by document.write can be a string (sequence of characters in quotes), or a combination of strings and variables connected with '+', which concatenates (joins end-to-end) the pieces together. Wherever a variable name appears in the message, its corresponding value will be substituted. For example, if "Dave" had been entered and stored in the variable firstName, then the above write statement would write the message
into the Web page. When the page is displayed in the browser, this message will appear along with any other text in the page.
In general, any message can be written and displayed in a Web page using a JavaScript write statement of the form:
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
would write the text
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.
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 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.
|
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 |
---|
|
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?
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. 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: 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." |
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".
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.
| |
| ||
| |
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:
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.
|
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:
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.
|
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 assignmentrefrain = "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(" Since the spelling assigned to the refrain variable is the same as before, the behavior of the page should not change.Old MacDonald had a farm, " + refrain + ".
");
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.
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.
|
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.
- It must be at least two paragraphs long.
- It must have at least six missing words.
- At least one of the missing words must be used multiple times in the story. For example, the person's name was used twice in the sample story above.
- The page should have a title, centered at the top, that includes your name.
Supplemental (optional) material and exercises | Solutions to odd numbered exercises |