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.
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.
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 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.
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 this example, the value being assigned is obtained 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 Lesson 3.) 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, which is referred to 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.
The remainder of this assignment statement causes the text entered by the user to be remembered under the name on the left side of the equals sign. In programming terminology, a variable is a name that is given to an arbitrary value so that the value can be remembered and referred to later. In this example, the text entered by the user is assigned to the variable name firstName, and any subsequent references to firstName will recall the user's text.
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 avariable 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 HTML document. When the page is displayed in the browser, this message will appear along with any other text in the HTML document.
In general, any message can be written to an HTML document and thus displayed in the 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 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
would write the text
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. |
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 |
---|
|
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?
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".
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:
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).
|
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.
|
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 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 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.
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.
- 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.
Additional (optional) exercises | Solutions to odd numbered exercises |