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
- This is a laboratory class. You will be doing many hands-on exercises and looking at many examples.
- Prerequites: HTML skills, some programming experience, and good PC skills. I will not be able to spend time teaching the basics.
- Software requirements: an editor (notepad, Frontpage, etc.) and a WWW browser (IE 4.0 or NS 4.0). If you log in as 'internet' you should have access to these things.
- Browser object model in Netscape and Internet Explorer
- Invented by Netscape in 1995 in Navigator 2.0.
- Designed as a browser, client-side scripting language for the Web, supplementing HTML.
- Similar syntax to C, C++, and Java.
- Interpreted, scripting language, not a full programming language.
- Also has been adopted by Microsoft: they call it "JScript".
- Has been proposed as a standard called ECMAScript. MS and NS are working to make their implementations
comply with the standard.
- Not really related to Java.
- But it is supported very unevenly between operating systems and between Netscape and Microsoft.
- Alternatives: CGI, Java, VBScript, Dynamic HTML, ASP.
- As a server-side scripting language for Microsoft Active Server Pages.
- As a server-side scripting language in Netscape Livewire.
- As a scripting language embedded in other applications.
- variables, constants (pieces of data)
- data structures like array and objects (ways to hold together and access bigger sets of data)
- user-defined functions
- built-in functions (math, dates, etc.)
- operators (+,-,/,*)
- statements (if, while, for)
- object-based programming (but not fully object-oriented)
But, it is most powerful when the language elements are combined with the "browser object model":
- Page elements
Your first program
- End tag with </SCRIPT>
- There are several places on an HTML page where script tags can go, and a page will often have several.
A simple example:
- Open the text editor of your choice (notepad, Frontpage, etc.)
- Make a blank HTML page.
- Copy this example into it.
- Load the page into your browser, and watch it go.
Other examples, using simple expressions
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.
The alert(), confirm(), and prompt() functions, with an if-else example
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
Operators and expressions
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");
Build a program that does the following:
- Asks the user for a measurement in inches.
- Tells the user the same measurement in centimeters(multiply by 2.54).
A user-defined function, and a while loop:
the Netscape notes at
Part 11, "Statements".
var MIN = 1;
var MAX = 10;
return (num >= MIN && num <= MAX);
var guess = prompt("Please enter a number between " + MIN + " and " + MAX,"");
guess = prompt("That guess was not between " + MIN + " and " + MAX + ", please try again.","");
Write a program to:
- Choose and store a random number between 1 and 1000.
- Allow the user to choose the number until getting it right.
- Tell the user in each turn whether the guess was too high or too low.
- Declare a variable to store the random number and populate it using the Math.random() function.
- The Math.floor( ) function rounds a number down to the next integer. You will need to use this.
- 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.
- Use a while loop to play the game until the user gets the right answer.
The for loop
See the notes for for
at the Netscape notes at
Part 11, "Statements".
var MAX = 10;
for (count = MAX; count >= 1; count--)
document.write("Countdown: " + count + "<BR>");
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)
the browser, and a developer can create objects.
at the Netscape notes at
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());
// 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>");
document.writeln("You are not using Netscape.<BR>");
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.
- Ask the user for his/her name.
- Tell the user how long the name is.
- Print the name in uppercase and lowercase.
- Print the first character of the name.
- Say whether the name contains the letter 'a'.
- Say whether the user is a Netscape or Internet Explorer user.
- Say whether the user is a Windows NT user.
at the Netscape notes at
var d = new Date(); // With an empty constructor, default to the current date
document.write("<h3>" + d.toString() + "</h3>");
Write a program that:
- Asks the user for the current date in the format MM/DD/YYYY.
- Tells the user how many days it is until the new year.
- There is a method of String called 'substring' which you can use to parse the user input.
- There is a Date() constructor which takes a year, month, and date as an argument.
- Look at the getTime() method of Date.
- Use Math.floor() for rounding.
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>");
Example: looping through all of the links in a document
for (count=0; count< window.document.links.length;count++)
document.write("Link " + count + ": " + window.document.links[count]+"<BR>");
Example: the status bar
The status bar for a window can be accessed as the 'status' field of the current window (window.status).
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.
Move your mouse over here and watch the status bar.
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
Syntax of event handlers:
For form elements:
The onClick() event, with a hyperlink:
<A HREF="index.html" onClick="alert('Thanks for clicking'); return true;">Click for a test</A><P>
Click for a test
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.
The onMouseOver() event:
alert("You got too close!")
<A HREF="somepage.html" onMouseOver="oops()">Move mouse over this for a test</A>
Move mouse over this for a test
The onChange() event:
<INPUT TYPE="text" NAME="text1" onChange="document.myform.text2.value = document.myform.text1.value"><BR>
<INPUT TYPE="text" NAME="text2">
The setTimeout() function
Try the following code:
setTimeout("alert('Time is up')",2000)
- Write a program to put an updating timer on the status bar
- Hint: window.status is the property that controls the status bar
- Hint: you need to write a function, but only one function
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!'">
triggered from these elements.
The documentation for the browser object models will show you the object hierarchy for reading and setting form elements.
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:
// 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.
if (theField.indexOf('@', 0) > 0 && (theField.indexOf('.',0) > theField.indexOf('@',0)))
alert("Your email address was an invalid format. Please try again.");
<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">
- Copy this form to your own page.
- Add a phone number field.
- Add a routine to validate phone number (format XXX-XXX-XXXX)
A library of form validation routines can be found at the Netscape WWW site.
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.
var val1, val2
val1 = parseInt(document.calcForm.val1.value)
val2 = parseInt(document.calcForm.val2.value)
result = val1 + val2
result = val1 - val2
document.calcForm.result.value = result
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"
- Copy this form to your own HTML page
- Add multiplication and division to the form
- 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.
- Hint: use the onChange event for the text fields, and use the onClick event for the radio buttons
Another example of a form similar to this one is at this uppercase/lowercase form.
- Build a inches to centimeters form with 2 text boxes
- Make it so that when you change the inches field, the proper conversion to centimeters is written into the centimeters box
- And, vice-versa
Frames and windows
Please look at this example at The Nature Conservancy. It is a great
An example that does frame manipulation is on this page.
- Create a frameset that has two frames, side by side.
- Make the left-hand frame contain a form with 3 radio buttons
- The buttons should be for three search engines:
When the user clicks on of the option buttons, the frame on the right hand side should be loaded with the right search engine.
- Yahoo (http://www.yahoo.com)
- Altavista (http://www.altavista.com)
- Infoseek (http://www.infoseek.com)
Example that will replace the first graphic on a page (image.gif) with another graphic (newgraphic.gif):
- Use frames, and put each image in a different frame.
- Change the image directly (only works in NS 3.0 and beyond and IE 4.0).
document.images.src = "newgraphic.gif"
- Build a WWW page with an image and 3 buttons.
- Pick your three favorite graphics out on the WWW.
- Label the buttons and make each one swap in the graphic you have chosen.
Opening and manipulating windows
The function to open a new window is 'window.open()'. Syntax and options are
var win = window.open(URL, name, options)
See notes on this page.
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.