Lesson 22: Dynamic Web Pages via JavaScript

Due by the beginning of class on Wednesday, Mar. 31

In this lesson, you will learn how to embed your JavaScript code in HTML documents, and so use the browser itself to execute your code. While the JavaScript interpreter that you have been using will still be useful for designing and testing pieces of code, the ability to integrate code with other HTML elements will open up a world of new possibilities.


Embedding JavaScript Code in HTML

Throughout this course, you have been writing and executing your JavaScript code in a simple interpreter environment. The JavaScript interpreter that you have been using was written specifically for this course, allowing you to learn programming with minimal overhead. The interpreter page is divided into two frames, one containing a text box for entering your code and a separate frame for displaying the output of your code. When you click on the Execute button in the input frame, the interpreter takes your code, embeds it in the appropriate HTML code, and then loads that code into the output frame. The actual execution of your code is performed by the Web browser itself.

Now that you know a little about how Web pages work, the interpreter page no longer is necessary (although it can still be useful). Instead, you can embed your JavaScript code directly into HTML documents and execute that code by loading the page into the browser. Not surprisingly, you must identify JavaScript code in the HTML document using tags. Any code surrounded by the tags <SCRIPT LANGUAGE="JavaScript"> and </SCRIPT> will be executed by the browser, and the resulting output of that execution will be displayed on the page.

For example, consider the following HTML document.

<HTML> <HEAD> <TITLE> Hello Page</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> document.write("Hello World Wide Web!<BR>"); </SCRIPT> </BODY> </HTML>

This page contains a single line of JavaScript code, which displays the message "Hello World Wide Web!". When this page is loaded into the browser, the SCRIPT tags identify code that is to be executed. The output of the code, in this case the single message, will appear on the Web page.

While this example is simple, it is not very compelling. In fact, you could easily achieve the same effect by entering this message as regular HTML text. Suppose, however, that you wanted to display the message some number of times in the page. It would be tedious to have to enter multiple copies of the message, and it would also be cumbersome if you decided to change the number of repetitions. On the other hand, JavaScript makes this task trivial:

<HTML> <HEAD> <TITLE> Repetitive Hello Page</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> for (i = 1; i <= 20; i++) { document.write("Hello World Wide Web!<BR>"); } </SCRIPT> </BODY> </HTML>


Exercise 1:     Cut-and-paste this HTML code into a document called hello.html. Then, load the page into the browser to execute the code and display the message 20 times. Note: to load a page that is stored as a local document on your computer, select "Open Page" from the File menu in the browser.


Exercise 2:     Within the SCRIPT tags, you can place any JavaScript code that you wish. For example, you can use alert and prompt to interact with the user. (There are nicer ways of interacting within a Web page, however, as you will see in a later lesson.) Modify the code in hello.html so that it displays a personalized greeting to the user. It should use the prompt function to read in the user's name, and then say "Hello" to that person 20 times.


Exercise 3:     Granted, the "Hello World" page is rather contrived. Consider a more plausible application. Suppose you are to write a Web page for the Psychic Acquaintances Network, a group of Web psychics. They would like to have a page which displays a "lucky" number (say between 1 and 100) every time the user loads the page. This can be done easily enough in JavaScript using the Math.random and Math.ceil functions.

Write the HTML code for such a page and save it in the document psychic.html. Load the page to execute your code and verify that it does indeed display a different "lucky" number every time. Feel free to elaborate.


Loading Libraries of Code

An important step in building abstractions for problem solving is library use. Useful routines can be encapsulated in a library file and then loaded whenever they are needed. The use of libraries simplifies programming and allows you to think at a higher level of abstraction.

The JavaScript interpreter had a special box in which you entered the names of any library files that were to be included. This same effect can be achieved in HTML by specifying the SRC attribute in the SCRIPT tag. For example, the following element, when included in an HTML document, will load the JavaScript library named random.js.

<SCRIPT LANGUAGE="JavaScript" SRC="random.js"></SCRIPT> Generally, elements such as these are inserted into the HEAD section of a page, as opposed to the BODY where other code is inserted. This is due to fact that the HEAD is loaded first, and so you are assured that the functions defined in the library are loaded before being called from the BODY.


Exercise 4:     Add the above element to your psychic.html page and modify the code to make use of the randomInt function defined there. Again, this element should be placed in the HEAD section, below the TITLE.

Note: it is assumed that library files are stored in the same directory as the page being loaded. This means that you will have to make a local copy of the random.js library to be stored along with your HTML documents. You can click on this link to view the contents of random.js, then cut-and-paste the code into a document (named random.js) in your home directory.


Defining Functions in a Page

With the exception of Turtle Graphics (which were specially handled by the interpreter), any JavaScript code that you wrote in the interpreter can be written directly in an HTML document. This includes function definitions. As was the case for loading libraries, function definitions should be defined in the HEAD section of the page to ensure that they are properly loaded before attempting to call them.

For example, the following HTML document contains the definition of the diceRoll function, which uses the randomInt function from random.js.

<HTML> <HEAD> <TITLE> Dice Roll </TITLE> <SCRIPT LANGUAGE="JavaScript" SRC="random.js"></SCRIPT> <SCRIPT LANGUAGE="JavaScript"> function diceRoll(numSides) // Given : numSides > 0 (an integer) // Returns: sum of two NumSides-sided dice rolls { return randomInt(1, numSides) + randomInt(1, numSides); } </SCRIPT> </HEAD> <BODY> Get ready to roll two six-sided dice... <BR><BR> <SCRIPT LANGUAGE="JavaScript"> document.write("You rolled " + diceRoll(6) + ".<BR>"); </SCRIPT> <BR> Wasn't that <I>exciting</I> ? </BODY> </HTML>

You should note that the JavaScript code in the BODY is mixed in with regular HTML text. This is certainly common, since most text in a Web page can be written directly without the use of JavaScript.


Exercise 5:     Cut-and-paste this HTML code into a document called craps.html. Then, load the page into the browser to execute the code and verify that it does produce random rolls of the dice.


Exercise 6:     A more interesting application involving dice is the casino game craps. Craps is a relatively easy game to understand:

Using pseudo-code, the algorithm for playing the game of craps can be described as follows:

ROLL DICE TO GET THE POINT (AND DISPLAY ROLL) if (POINT IS 7 or 11) { DISPLAY WINNING MESSAGE } else if (POINT IS 2, 3, or 12) { DISPLAY LOSING MESSAGE } else { ROLL DICE AND DISPLAY ROLL while (ROLL IS NOT POINT AND IS NOT A 7) { ROLL DICE AND DISPLAY ROLL } if (ROLLED THE POINT) { DISPLAY WINNING MESSAGE } else { DISPLAY LOSING MESSAGE } } Fill in the details of this pseudo-code and place the resulting code in the BODY of craps.html. Each time you load this page, you should have a new craps game displayed. Feel free to elaborate.


Lesson Summary


Solutions to odd numbered exercises (posted late afternoon of due date).