CSC 105 Grinnell College Spring, 2005
 
An Algorithmic and Social Overview of Computer Science
 

Laboratory Exercises on an Introduction to JavaScript

Abstract

Now that we have seen some basics about formatting Web pages with html, we consider processing within those pages. More specifically, in this lab, we consider three general topics:

  1. events, user actions that trigger processing within a Web page,
  2. JavaScript, a programming language that provides a mechanism to respond to user events, and
  3. background colors, colors that provide a general appearance to a page or page segments.

The next lab introduces two additional topics:

  1. pop-up windows, new windows that present information or other Web pages to the user, and
  2. error checking, the use of JavaScript to check input provided by users for mistakes.

We proceed by considering an extended example. Although this example is limited in scope, the goal is to introduce some basic capabilities. With this background, you could explore more details on your own, as your interests dictate.

Note

For this lab, you should check that your browser is set to enable JavaScript to be used. If your browser normally has JavaScript disabled, please enable it for the duration of this lab −− you can disable JavaScript again after the lab is over.

Events

An event is a user action, such as clicking a mouse button, typing in a text box, loading a page, leaving a page, or clicking "submit" on a form. Many dynamic Web pages contain instructions, so that an event triggers some response. In the jargon of Web programming, the instructions for responding to an event are packaged in what is called an event handler.

Since the notions of events and event handlers may seem abstract, this lab provides first-hand experience with several types of events and handlers.

  1. Load the page sample-form-js.html into your browser, and record what happens in each of the following circumstances:
    1. When the page loads (click the browser's reload button a few times to be sure you know what happens with each page load).
    2. When you move the mouse over the box identified by the caption, "Enter some text here".
    3. When you enter some text (with both capital letters and lower case letters) in the box for "Enter some text here".
    4. When you enter some text (perhaps a number) under "Enter a number here" and click to another place on the page (do this several times to be sure).
    5. When you enter some text (perhaps a number) under "Enter a another number here" and click to another place on the page.
    6. When you enter a six-character RGB color code in box for "Pick a background color here", and then click on another place on the page.
    7. When you fill in each field and click "Submit Data".

  2. After reviewing your experience with step 1, identify various actions or events that made something change. For example, did a response happen when you moved the mouse, when you clicked the mouse, etc.?

  3. After viewing sample-form-js.html in your browser, save it to your public_html subdirectory of your account, set its permission code to be accessible over the Web, and check that you can view it in your browser.

  4. Load your copy of sample-form-js.html into an editor, so you can examine and edit this file.

We now examine how sample-form-js.html identifies events and specifies how those events will be handled.

JavaScript

sample-form-js.html follows the same general format as the html pages we have seen previously, with one significant addition: Several JavaScript functions are defined near the beginning of the page. More precisely, the first part of the page contains descriptions of these functions:

This section of JavaScript definitions begins with the line


    <script LANGUAGE="JavaScript" type="text/javascript">
and ends with the line

    </script>
Within this section, note that some lines are inserted as commentary; they do not provide processing instructions, but rather allow the human programmer to better understand and organize these programming instructions. These comments begin with the characters //

To see how JavaScript can be used to handle specified events, consider the following function:


///***********************************************************************/
// This function adjusts the background color of this page
function pickBackgroundColor ()
{
   var colorString = pickRandomColor();
   top.document.sampleForm.yourColor.value = colorString;
   top.document.bgColor = colorString;
}
Since the first two lines of this listing begin with //, these entire lines are comments for us to help us understand what follows.

The line function pickBackgroundColor () indicates the start of a description for processing −− that is, the start of a function.

The braces { and } mark the activities for this function. In this case, the function involves three instructions:

(Note that all instructions in JavaScript end with a semicolon.)

Overall, this function changes the background of the page to a random color and records this color in the "Current/designed background color" text box.

The onLoad Event

To see how this JavaScript function may be used, look at the body tag for this Web page:


<body onLoad="pickBackgroundColor();">

Here onLoad provides a directive when you first load the page. That is, onLoad identifies a specific event, and the rest of that line indicates what handler should be used in response to these events. Overall, this line specifies that the browser should use the JavaScript function pickBackgroundColor to respond to an onLoad event.

  1. Change your copy of sample-form-js.html, so that the page has background color blue ("#0000FF") when it first loads, rather than choosing a random color.

  2. Change your copy of sample-form-js.html, so that the page sets the background to a color of your own choosing when it first loads.

More About Background Color −− an onChange Event

Now consider the text box for "Current/desired background color:". You can adjust the value shown in this box by clicking in the text area and typing. When you move from this box to somewhere else, the "onChange" event is triggered.

  1. Look at the input box for "Current/desired background color" to determine what handler is associated with this "onChange" event. That is, what JavaScript function is called after you change the text in this box?

The input tag lists the parameter this for this handler. In this context, this refers to the specific input box with the name yourColor.

Now look at the corresponding JavaScript function. Here the function has a parameter theField that refers to the information supplied when we identified the event. That is, theField refers to the input box for yourColor. The expression theField.value then retrieves the current text that we have typed within this box.

Within the function, the expression top refers to the overall window, just as we saw in our lab on frames. The expression top.document then refers to the entire material that appears within that browser window. Finally, the expression top.document.bgColor refers to the background color of this browser window, and


   top.document.bgColor = theField.value;

changes this background color to the text that we typed in the text box.

  1. Suppose the above line is changed to

    
       top.document.bgColor = "#660066";
    

    Describe what happens when you type a different value into this text box, and explain why.

With this discusion on changing the background color of a page, let us consider how the function pickRandomColor works. The idea is to choose a color for red, green, and blue randomly. To do this, function pickHexDigit selects a hexadecimal digit (0, 1, 2, ..., 9, A, B, C, D, E, F) at random. The function pickRandomColor then uses pickHexDigit twice to choose a two-digit hexadecimal number for red. pickRandomColor follows a similar process to choose a random two-digit hexadecimal number for green, and again for blue. The last line


   return "#" + r + g + b;

combines these red, green, and blue values into a single string of characters, with a number sign at the start. This is the combined RGB value specified by the pickRandColor function.

Functions adjustBackgroundColor and adjustRowColor use the RGB value given by pickRandomColor to get a colorString. When you change the text typed in the box for "Enter a number here", the event handler adjustBackgroundColor uses that RGB value to set the page's background color and to update the box for "Pick a background color".

  1. Change pickRandomColor, so that values for red, green, and blue are the same.

  2. Modify adjustColor, so it also modifies the box entitled "Enter some text here" to display the comment, "Nice background color!"

Modifying Colors in Other Sections

Next consider the boxes with the captions "Enter a number here" and "Enter another number here". The input boxes for these form elements include an onChange event. Such an event is triggered after you have typed or deleted text within the box and then move to another area of the page; that is, an onChange event occurs after you have finished changing a text input box.

In this case, the onChange event calls an adjustRowColor handler. In looking more closely at adjustRowColor, the first parameter identifies the name (or id) for a part of a table. In particular, 'numberdescription' and 'anotherdescription' are id's given to two parts of the table on this page. The second parameter to adjustRowColor uses the word this to specify which input box is being processed.

Within adjustRowColor, the first line gets a random color. The second line displays this color in the "Current/update background color" box, and then changes the color of the font used for both the caption and the text in the input box.

  1. Within sample-form-js.html, find the input box corresponding to the caption "Enter another number here". In the specification of adjustRowColor, change the first parameter from 'anotherdescription' to 'numberdescription'. Now reload the page and type some text into the various text boxes. Describe what happens.

  2. With the input box with the caption "Enter another number here", change the first parameter of adjustRowColor to 'textsection'. Reload the page, describe what happens when you change the text in that input box, and explain why that result occurs.

The onmouseover and onmouseout Events

Next, consider the events associated with the input box with the caption "Enter some text here". As with previous text boxes that we have discussed, the onChange event is triggered when we finish editing text in a box and then move to another part of the page. In this case, the event handler is adjustText that takes the letters within the input box and changes any upper-case letters to lower case.

  1. Within the adjustText function, change toLowerCase to toUpperCase. After reloading the page in your browser, type some text into this text box, move the mouse to somewhere else on the page, and describe what happens.

This text box also specifies two remaining events:

In this case, event handler adjustBackgroundColor changes the background color for an input box, and restoreBackgroundColor changes the color back. As a technical detail, adjustBackgroundColor must store the old color, previously in a box, so we can retrieve that color designation later on.

  1. Read the instructions for adjustBackgroundColor and try to outline how it works.

  2. Read the instructions for restoreBackgroundColor and try to outline how that works.

  3. Change adjustBackgroundColor so that the color of the box changes to blue each time, rather than choosing a random color.

  4. What happens if you delete the line onmouseout="restoreBackgroundColor(this)"; from the event handler for the input box with the caption "Enter some text here". (After answer this question, restore the Web page to the way it was before this step before going on.)

  5. Change the events associated with the input box for "Enter a number here", so that the background changes to blue when you move a mouse over this text box, and so that the background color is restored to its previous color when you move the mouse away.

Work To Be Turned In



This laboratory exercise coordinates with Chapter 12 of Walker, Henry M., The Tao of Computing: A Down-to-earth Approach to Computer Fluency, Jones and Bartlett, March 2004.
created 17 December 2003
last revised 13 May 2006

Valid HTML 4.01! Valid CSS!