1999 Schedule

Programming Web Pages with JavaScript

Until recently, Web-site design was limited by the constraints of HTML and CGI. JavaScript is an easy-to-use language, developed by Netscape, which can be embedded in HTML pages to make them more interactive and dynamic.

JavaScript allows site designers with moderate programming skills to add capabilities to their Web pages, including instant user feedback, advanced form processing, pop-up windows, advanced frame applications, and much more. You learn the basic elements of the JavaScript language and several techniques to take your Web pages to the next level.

Prerequisite: Familiarity with HTML and Web page design. Some programming experience in C, Visual Basic, or the equivalent.

MICHAEL WOLFE, M.S., is Vice President of Engineering at Kana Communications, a startup software company focusing on enterprise email support solutions. He has been teaching computer science and developing industrial systems for 10 years at Stanford University, Goldman Sachs, and Wells Fargo. His prior position was as a Director of Engineering of Internet Profiles Corp.

2 days, Feb. 6-7, 8:30 am-5:30 pm

Introduction

Class Outline

JavaScript is a language

JavaScript is a way to enhance WWW pages within a WWW browser

JavaScript can also be used elsewhere

Examples

Resources

JavaScript contains many of the same elements that other programming languages do:

But, it is most powerful when the language elements are combined with the "browser object model":

Your first program

One way to put JavaScript in a page is with the <SCRIPT> tag

A simple example:

<SCRIPT LANGUAGE="javascript">
document.write("Hello, world")
</SCRIPT>

Output:

Assignment:

  1. Create a working folder on your PC for your JavaScript exercises.
  2. You do not necessarily need to run a WWW server to develop JavaScript, since you can do it all locally. If you want to run one for practice, go ahead.
  3. Open the text editor of your choice (notepad, Frontpage, etc.)
  4. Make a blank HTML page.
  5. Copy this example into it.
  6. Load the page into your browser, and watch it go.

Other examples, using simple expressions

<SCRIPT LANGUAGE="javascript">
// This JavaScript illustrates some simple concepts
document.write("<B>Hello, bold world</B><BR>")					// Print text with an HTML tag
document.write("Two plus two is " + (2+2) + "<BR>")				// Print the result of a mathematical expression
document.write("Your browser says it is: "\" + navigator.userAgent + "\"<BR>")	// Print one of the browser properties.
</SCRIPT>

Output:

The alert(), confirm(), and prompt() functions, with an if-else example

We are first going to look at some examples of JavaScript functions. A function is an expression that does something...kind of like a verb. Several functions are either built into the JavaScript language or are built into the browsers in which JavaScript runs. Most of the useful functions, including the ones we are looking at here, are built into both the Netscape and Microsoft browsers. We can look at the notes at Netscape to see how these functions work. Go under Part 13 to see links to all available functions, including alert(), confirm(), and prompt(). Use that documentation to figure out how the following code works.

var yourName;						// Declare a variable called yourName, which will store your name after you type it in
yourName = prompt("What is your name?", "");		// Now read the name from the user and store it

if (confirm("Do you want to play a game, " + yourName	+ "?"))		// Ask if the user wants to play.  confirm() returns either true or false
{
	alert("OK. let's play, " + yourName);		// alert() pops up a browser dialog box
}
else
{
	alert("Too bad!");
}

The JavaScript above is on this page.

Operators and expressions

JavaScript has all of the usual mathematical and logical operators. Please see documentation at Part 7, "Expressions and Operators" at the Netscape notes.
+, -, /, % (arithmetic)
>, <, >=, lt=, ==, != (comparisons)
&&, ||, ! (boolean)

Another example, using a variable and the if-else statement.

The if-else statement is documented at the Part 11, "Statements".


// This is a comment (starting with a // on the same line)
// here, we hardcode the right answer (but, JS also has a Random() function you could use to generate a new one each time)
var rightAnswer = 57;

var num = prompt("Please guess a number below 100: ","");

/* This is another comment.  You would use this syntax for
   a comment that spans multiple lines */

if (num < rightAnswer)
{
   alert("Your guess was too low");
}
else if (num > rightAnswer)
{
   alert("Your guess was too high");
}
else
{
   alert("Congratulations!");
}

Assignment:

Build a program that does the following:

  1. Asks the user for a measurement in inches.
  2. Tells the user the same measurement in centimeters(multiply by 2.54).
A solution.

A user-defined function, and a while loop:

In JavaScript, you can create your own functions. See the notes for function() and for the while() statement at the Netscape notes at Part 11, "Statements".

var MIN = 1;
var MAX = 10;

function goodGuess(num)
{
	return (num >= MIN && num <= MAX);
}

var guess = prompt("Please enter a number between " + MIN + " and " + MAX,"");

while (!goodGuess(guess))
{
   guess = prompt("That guess was not between " + MIN + " and " + MAX + ", please try again.","");
}

Assignment:

Write a program to:
  1. Choose and store a random number between 1 and 1000.
  2. Allow the user to choose the number until getting it right.
  3. Tell the user in each turn whether the guess was too high or too low.
Hints:
  1. Declare a variable to store the random number and populate it using the Math.random() function.
  2. The Math.floor( ) function rounds a number down to the next integer. You will need to use this.
  3. Write a function to give user feedback on whether the number was too high or too low and return a true if the answer was correct and false if it was not.
  4. Use a while loop to play the game until the user gets the right answer.
A solution.

The for loop

See the notes for for at the Netscape notes at Part 11, "Statements".

 
var MAX = 10;
var count;
for (count = MAX; count >= 1; count--)
{
   document.write("Countdown: " + count + "<BR>");
}

Output:

The most important JavaScript object: String().

An object is a programming construct that usually represents a real world concept. An object, in most languages, can contain data (the current object state) and methods, which are functions that can be called upon that object. Several objects are defined by JavaScript, several more are provided by the browser, and a developer can create objects.

Strings are used everywhere in JavaScript. See the notes for String at the Netscape notes at Part 13, "Netscape JavaScript Reference".

The String constructor:
The constructor is the operator to create a new instance of an object. Each object is documented with all of its various constructors.

var str = new String("Hello");  // The basic constructor
var str2 = "Hello";		// This is shorthand and is what is usually used   
String properties methods:
The String object is documented with a set of methods and properties it has available. In particular, length, indexOf(), toUpperCase(), and toLowerCase() are useful.
alert("Your name is " + str.length + " characters long");
alert("Your name in uppercase is " + str.toUpperCase());
Browser detection:
<SCRIPT LANGUAGE="javascript">

// Print out the browser name and version (these are properties of the object called 'navigator'
document.write(navigator.appName + "< BR>")
document.write(navigator.appVersion + "<BR>")

if (navigator.appName.indexOf("Netscape") != -1)
{
  document.writeln("You are using Netscape.<BR>");
}
else
{
  document.writeln("You are not using Netscape.<BR>");
}
</SCRIPT>
Output:

Assignment: Look at the documentation for the String class at the Netscape notes and write a script to:

Hint: see these notes under User Info for common browser and OS strings.

Another JavaScript Object: the Date() class

One object built into JavaScript is Date. See the notes for Date at the Netscape notes at Part 13, "Netscape JavaScript Reference".

Date example

var d = new Date(); // With an empty constructor, default to the current date
document.write("<h3>" + d.toString() + "</h3>");

Output:

Assignment:

Write a program that:

  1. Asks the user for the current date in the format MM/DD/YYYY.
  2. Tells the user how many days it is until the new year.
Hints:

  1. There is a method of String called 'substring' which you can use to parse the user input.
  2. There is a Date() constructor which takes a year, month, and date as an argument.
  3. Look at the getTime() method of Date.
  4. Use Math.floor() for rounding.
Solution.

Browser object model in Netscape and Internet Explorer.

Each major browser (Netscape 2.0, 3.0, 4.0 and Internet Explorer 3.0 and 4.0) exposes the major browser elements as an API (application programming interface) that the programmer has access to read and, sometimes, write to. They are charted as follows:

Netscape Navigator browser object model

Example: attributes of this page

document.write("window.location: <B>" + window.location + "</B><BR>");
document.write("window.document.referrer: <B>" + window.document.referrer + "</B><BR>");
document.write("window.document.bgcolor: <B>" + window.document.bgcolor + "</B><BR>");
document.write("navigator.appName: <B>" + navigator.appName + "</B><BR>");
document.write("navigator.appVersion: <B>" + navigator.appVersion + "</B><BR>");

Output:

Example: looping through all of the links in a document

var count;
for (count=0; count< window.document.links.length;count++)
{
  document.write("Link " + count + ": " + window.document.links[count]+"<BR>");
}

Output:

Example: the status bar

The status bar for a window can be accessed as the 'status' field of the current window (window.status).

Example:

Move your mouse over <A HREF="http://www.examiner.com" onMouseOver="window.status='Click for the examiner'; return true">here</A>  and watch the status bar.

Output:

Move your mouse over here and watch the status bar.

Events.

Events are asynchronous actions that happen when the user interacts with a page by typing, clicking, moving the mouse, or loading and unloading a page. Events can also be driven by timers. A reference of events can be found at the Netscape JavaScript documentation.

Syntax of event handlers:

For hyperlinks:
<A HREF="URL" event="some javascript">

For form elements:

<INPUT TYPE="type" NAME="name" event="some javascript">

The onClick() event, with a hyperlink:

<A HREF="index.html" onClick="alert('Thanks for clicking'); return true;">Click for a test</A><P>
Note: if the JavaScript called from the onClick event returns a true value, the link is followed. Otherwise, it is not.

Try it:

Click for a test

Assignment:

Create a hyperlink where the user is first warned "are you sure?" before the link is followed. If the user cancels, then the link is not followed.

Create another hyperlink where the user gets asked a "secret" password before continuing. If the user gets the password right, the link is followed.

Solution.

The onMouseOver() event:

<SCRIPT LANGUAGE="javascript">
function oops()
{
	alert("You got too close!")
}
</SCRIPT>

<A HREF="somepage.html" onMouseOver="oops()">Move mouse over this for a test</A>

Try it:

Move mouse over this for a test

The onChange() event:

<FORM NAME=myform>
<INPUT TYPE="text" NAME="text1" onChange="document.myform.text2.value = document.myform.text1.value"><BR>
<INPUT TYPE="text" NAME="text2">
</FORM>
Result:

FROM Field:
TO Field:

The setTimeout() function

Try the following code:

setTimeout("alert('Time is up')",2000)

Assignment:

Solution.

The onLoad() function

This event occurs when the page has been fully loaded. Pages can take a long time to load, and there are often times when you don't want to execute a command until the page is done loading. Try the following code somewhere in the BODY tag on your page:

<BODY onLoad="window.status = 'Fully loaded!'">

Forms

Much JavaScript interaction is done via HTML forms and their familiar elements: buttons, text boxes, radio buttons, check boxes, text boxes, etc. In JavaScript it is possible to control these elements as well as respond to events triggered from these elements.

The documentation for the browser object models will show you the object hierarchy for reading and setting form elements.

JavaScript is often used for validating fields in forms. The following example shows how JavaScript can be used to validate the email address of a form in the user's browser before it gets submitted to the server:

E-mail address validation example:

<SCRIPT LANGUAGE="javascript">

// Check for a valid email address (Does it contain a "@", followed
// by a '.'. Return True if it is valid and false if not.
// Also alert the user with an error message.
//
function checkEmail(theField) 
{
   if (theField.indexOf('@', 0) > 0 && (theField.indexOf('.',0) > theField.indexOf('@',0)))
   {
      return true;
   } 
   else 
   {
      alert("Your email address was an invalid format.  Please try again.");
      return false;
   }
}
</SCRIPT>

<FORM NAME=emailform ACTION="yourcgihere.cgi" METHOD=POST onSubmit="return checkEmail(window.document.emailform.emailAddress.value)">
Please enter your email address:<P>
<INPUT TYPE=text NAME="emailAddress" VALUE=""><P>
<INPUT TYPE=submit NAME="Submit" VALUE="Submit">
</FORM>

Output:

Please enter your email address:

Assignment:

  1. Copy this form to your own page.
  2. Add a phone number field.
  3. Add a routine to validate phone number (format XXX-XXX-XXXX)
Solution.

A library of form validation routines can be found at the Netscape WWW site.

Calculator examples

These are examples of forms that do not send any data to the server but tries to do a useful operation in the browser itself.

This is an example of a mortgage calculator.

<SCRIPT>
function doCalculate()
{
   var val1, val2
   var result
   val1 = parseInt(document.calcForm.val1.value)
   val2 = parseInt(document.calcForm.val2.value)
   if (document.calcForm.op[0].checked)
   {
   result = val1 + val2
   }
   else
   {
   result = val1 - val2
   }
   document.calcForm.result.value = result
}
</SCRIPT>

<FORM NAME="calcForm">
Value 1:<INPUT TYPE=text NAME="val1" SIZE=6><P>
Add:<INPUT TYPE=radio NAME="op" VALUE="plus">
Subtract:<INPUT TYPE=radio NAME="op" VALUE="minus"><BR>
Value 2:<INPUT TYPE=text NAME="val2" SIZE=6><BR>
Result:<INPUT TYPE=text NAME="result" SIZE=10><BR>
<INPUT TYPE=button NAME="calculate" VALUE="Calculate" 
 onClick="doCalculate()">
</FORM>

Result:

Value 1:

Add: Subtract:
Value 2:
Result:

Assignment:

  1. Copy this form to your own HTML page
  2. Add multiplication and division to the form
  3. When you have this working, get rid of the 'Calculate' button, and make it so that the calcuation happens whenever you make a change to either value or click on the radio button.
  4. Hint: use the onChange event for the text fields, and use the onClick event for the radio buttons
Solution.

Another example of a form similar to this one is at this uppercase/lowercase form.

Assignment:

  1. Build a inches to centimeters form with 2 text boxes
  2. Make it so that when you change the inches field, the proper conversion to centimeters is written into the centimeters box
  3. And, vice-versa
Solution.

Frames and windows

JavaScript is very commonly used to control pages with complex frame layouts and to control multiple windows.

Frame manipulation:

Real-world example:

Please look at this example at The Nature Conservancy. It is a great example of using multiple frames on a page with JavaScript for a very useful and interesting effect.

Example:

An example that does frame manipulation is on this page.

Assignment:

  1. Create a frameset that has two frames, side by side.
  2. Make the left-hand frame contain a form with 3 radio buttons
  3. The buttons should be for three search engines:
  4. When the user clicks on of the option buttons, the frame on the right hand side should be loaded with the right search engine.
Solution.

Manipulating images

There are two ways to change an image on a WWW page using Javascript:

  1. Use frames, and put each image in a different frame.
  2. Change the image directly (only works in NS 3.0 and beyond and IE 4.0).
Example that will replace the first graphic on a page (image.gif) with another graphic (newgraphic.gif):

<IMG SRC="image.gif">

<SCRIPT LANGUAGE="javascript">
document.images[0].src = "newgraphic.gif"
</SCRIPT>
Exercise:

Solution.

Opening and manipulating windows

The function to open a new window is 'window.open()'. Syntax and options are at Netscape.

Usage:

var win = window.open(URL, name, options)

Example:

See notes on this page.

Assignment:

First, write a simple (one-line) JavaScript program to experiment with opening a window. Try all of the different options that you can (width, height, toolbars, location, status, resizable, etc.).

Repeat the assignment with the three search engines. Add two buttons, one to open a search engine window, and one to close it (use the close() method of window). Make it so that selecting the the radio button fills in the pop up window with the right site.

Another idea: pop up a very small "remote control" window. Allow the user to type a URL into that window to change the location of the larger window.