by Jim O'Donnell
The JavaScript language, which was first introduced by Netscape in their Web browser, Netscape Navigator 2, gives Web authors another way to add interactivity and intelligence to their Web pages. JavaScript code is included as part of the HTML document and doesn't require any additional compilation or development tools other than a compatible Web browser. In this chapter, you will learn about JavaScript and get an idea of the sorts of things it can do.
JavaScript allows you to embed commands in an HTML page. When a compatible Web browser, such as Netscape Navigator 2 or higher or Internet Explorer 3, downloads the page, your JavaScript commands are loaded by the Web browser as a part of the HTML document. These commands can be triggered when the user clicks page items, manipulates gadgets and fields in an HTML form, or moves through the page history list.
Some computer languages are compiled; you run your program through a compiler, which performs a one-time translation of the human-readable program into a binary that the computer can execute. JavaScript is an interpreted language; the computer must evaluate the program every time it's run. You embed your JavaScript commands within an HTML page, and any browser that supports JavaScript can interpret the commands and act on them.
JavaScript is powerful and simple. If you've ever programmed in
dBASE or Visual Basic, you'll find JavaScript easy to pick up.
If not, don't worry, this chapter will have you working with JavaScript
in no time.
| NOTE |
Java offers a number of C++-like capabilities that were purposefully omitted from JavaScript. For example, you can access only the limited set of objects defined by the browser and its Java applets, and you can't extend those objects yourself. For more details on Java, see the other chapters in Part XI, "JavaScript and Java. |
HTML provides a good deal of flexibility to page authors, but HTML by itself is static; once written, HTML documents can't interact with the user other than by presenting hyperlinks. Creative use of CGI scripts, which run on Web servers, has made it possible to create more interesting and effective interactive sites, but some applications really demand programs or scripts that are executed by the client.
JavaScript allows Web authors to write small scripts that execute on the users' browsers instead of on the server. For example, an application that collects data from a form and then posts it to the server can validate the data for completeness and correctness before sending it to the server. This can greatly improve the performance of the browsing session since users don't have to send data to the server until it's been verified as correct.
Another important use of Web browser scripting languages like JavaScript comes as a result of the increased functionality being introduced for Web browsers in the form of Java applets, plug-ins, ActiveX Controls, and VRML objects and worlds. Each of these things can be used to add extra functions and interactivity to a Web page. Scripting languages act as the glue that binds everything together. A Web page might use an HTML form to get some user input and then set a parameter for an ActiveX Control based on that input. It is a script that will usually actually carry this out.
JavaScript provides a fairly complete set of built-in functions and commands, allowing you to perform math calculations, manipulate strings, play sounds, open up new windows and new URLs, and access and verify user input to your Web forms.
Code to perform these actions can be embedded in a page and executed when the page is loaded. You can also write functions containing code that is triggered by events you specify. For example, you can write a JavaScript method that is called when the user clicks the Submit button of a form, or one that is activated when the user clicks a hyperlink on the active page.
JavaScript can also set the attributes, or properties,
of ActiveX Controls, Java applets, and other objects present in
the browser. This way, you can change the behavior of plug-ins
or other objects without having to rewrite them. For example,
your JavaScript code could automatically set the text of an ActiveX
Label Control based on what time the page is viewed.
| CAUTION |
If you read this chapter and Chapter 48, "ActiveX Scripting: VB Script and JScript," you will see that JavaScript and VB Script are very similar, with similar syntax and capabilities. Because of this, some of the material presented in this chapter is repeated in Chapter 48 However, JavaScript and VB Script are different languages and you should be careful not to mix them up when you are programming. |
JavaScript commands are embedded in your HTML documents. Embedding JavaScript in your pages requires only one new HTML element: <SCRIPT> and </SCRIPT>. The <SCRIPT> element takes the attribute LANGUAGE, which specifies the scripting language to use when evaluating the script.
JavaScript itself resembles many other computer languages. If you're familiar with C, C++, Pascal, HyperTalk, Visual Basic, or dBASE, you'll recognize the similarities. If not, don't worry-the following are some simple rules that will help you understand how the language is structured:
| NOTE |
If you're a Java, C, or C++ programmer, you might be puzzled when looking at JavaScript programs-sometimes, each line ends with a semicolon, sometimes not. In JavaScript, unlike those other languages, the semicolon is not required at the end of each line |
Even though JavaScript is a simple language, it's quite expressive. In this section, you learn a small number of simple rules and conventions that will ease your learning process and speed your use of JavaScript.
Hiding Your Scripts You'll probably be designing pages that may be seen by browsers that don't support JavaScript. To keep those browsers from interpreting your JavaScript commands as HTML-and displaying them-wrap your scripts as follows:
<SCRIPT LANGUAGE="JavaScript">
<!-- This line opens an HTML comment
document.write("You can see this script's output, but not its source.")
<!-- This line opens and closes a comment -->
</SCRIPT>
The opening <!-- comment causes Web browsers that do not support JavaScript to disregard all text they encounter until they find a matching -->, so they don't display your script. You do have to be careful with the <SCRIPT> tag, though; if you put your <SCRIPT> and </SCRIPT> block inside the comments, the Web browser will ignore them also.
Comments Including comments in your programs to explain what they do is usually good practice-JavaScript is no exception. The JavaScript interpreter ignores any text marked as comments, so don't be shy about including them. You can use two types of comments: single-line and multiple-line.
Single-line comments start with two slashes (//), and they're limited to one line. Multiple-line comments must start with /* on the first line and end with */ on the last line. Here are a few examples:
// this is a legal comment / illegal -- comments start with two slashes /* Multiple-line comments can be spread across more than one line, as long as they end. */ /* illegal -- this comment doesn't have an end! /// this comment's OK, because extra slashes are ignored //
| CAUTION |
Be careful when using multiple-line comments-remember that these comments don't nest. For instance, if you commented out a section of code in the following way, you would get an error message /* Comment out the following code The preferred way to create single-line comments to avoid this would be as follows: /* Comment out the following code |
Using <NOSCRIPT> You can improve the compatibility of your JavaScript Web pages through the use of the <NOSCRIPT>...</NOSCRIPT> HTML tags. Any HTML code that is placed between these container tags will not appear on a JavaScript-compatible Web browser but will be displayed on one that is not able to understand JavaScript. This allows you to include alternative content for your users that are using Web browsers that don't understand JavaScript. At the very least, you can let them know that they are missing something, as in the following example:
<NOSCRIPT> <HR>If you are seeing this text, then your Web browser doesn't speak JavaScript!<HR> </NOSCRIPT>
JavaScript was designed to resemble Java, which in turn looks
a lot like C and C++. The difference is that Java was built as
a general-purpose object language, while JavaScript is intended
to provide a quicker and simpler language for enhancing Web pages
and servers. In this section, you learn the building blocks of
JavaScript and how to combine them into legal JavaScript programs.
| NOTE |
JavaScript was developed by the Netscape Corporation, which maintains a great set of examples and documentation for it. Its JavaScript Authoring Guide is available on the CD-ROMs that accompany this book and can also be found online a http://home.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html |
An identifier is just a unique name that JavaScript uses to identify a variable, method, or object in your program. As with other programming languages, JavaScript imposes some rules on what names you can use. All JavaScript names must start with a letter or the underscore character, and they can contain both upper- and lowercase letters and the digits 0 through 9.
JavaScript supports two different ways for you to represent values in your scripts: literals and variables. As their names imply, literals are fixed values that don't change while the script is executing, and variables hold data that can change at any time.
Literals and variables have several different types; the type is determined by the kind of data that the literal or variable contains. The following are some of the types supported in JavaScript:
JavaScript is modeled after Java, an object-oriented language.
An object is a collection of data and functions that have
been grouped together. A function is a piece of code that
plays a sound, calculates an equation, or sends a piece of e-mail,
and so on. The object's functions are called methods and
its data are called its properties. The JavaScript programs
you write will have properties and methods and will interact with
objects provided by the Web browser, its plug-ins, Java applets,
ActiveX Controls, and other things.
| NOTE |
Though the terms function and method are often used interchangeably, they are not the same. A method is a function that is part of an object. For instance, writeln is one of the methods of the document object |
| TIP |
Here's a simple guideline: An object's properties are the information it knows; its methods are how it can act on that information |
Using Built-In Objects and Functions Individual JavaScript elements are objects. For example, string literals are string objects and they have methods that you can use to change their case, and so on. JavaScript can also use the objects that represent the Web browser in which it is executing, the currently displayed page, and other elements of the browsing session.
You access objects by specifying their name. For example, the active document object is named document. To use document's properties or methods, you add a period and the name of the method or property you want. For example, document.title is the title property of the document object, and explorer.length calls the length member of the string object named explorer. Remember, literals are objects, too.
Using Properties Every object has properties, even literals. To access a property, just use the object name followed by a period and the property name. To get the length of a string object named address, you can write the following:
address.length
You get back an integer that equals the number of characters in the string. If the object you're using has properties that can be modified, you can change them in the same way. To set the color property of a house object, just use the following line:
house.color = "blue"
You can also create new properties for an object just by naming them. For example, say you define a class called customer for one of your pages. You can add new properties to the customer object as follows:
customer.name = "Joe Smith" customer.address = "123 Elm Street" customer.zip = "90210"
Finally, knowing that an object's methods are just properties is important. You can easily add new properties to an object by writing your own function and creating a new object property using your own function name. If you want to add a Bill method to your customer object, you can do so by writing a function named BillCustomer and setting the object's property as follows:
customer.Bill = BillCustomer;
To call the new method, you use the following:
customer.Bill()
Array and Object Properties JavaScript objects store their properties in an internal table that you can access in two ways. You've already seen the first way-just use the properties' names. The second way, arrays, allows you to access all of an object's properties in sequence. The following function prints out all the properties of the specified object:
function DumpProperties(obj, obj_name) {
result = "" // set the result string to blank
for (i in obj)
result += obj_name + "." + i + " = " + obj[i] + "\n"
return result
}
So not only can you access all of the properties of the document object, for instance, by property name, using the dot operator (for example, document.href), you can also use the object's property array (for example, document[1], though this may not be the same property as document.href). JavaScript provides another method of array access that combines the two, known as associative arrays. An associative array associates a left- and right-side element, and the value of the right side can be used by specifying the value of the left side as the index. Objects are set up by JavaScript as associative arrays with the property names as the left side, and their values as the right. So the href property of the document object could be accessed using document["href"].
JavaScript has a lot to offer page authors. It's not as flexible as C or C++, but it's quick and simple. Most importantly, it's easily embedded in your WWW pages so that you can maximize their impact with a little JavaScript seasoning. This section covers the gritty details of JavaScript programming, including a detailed explanation of the language's features.
A full language reference for JavaScript is included on the CD-ROMs that come with this book. Since JavaScript is an evolving language, you can get up-to-the-minute information on it at Netscape's JavaScript Authoring Guide Web site at
http://home.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html
An expression is anything that can be evaluated to get a single value. Expressions can contain string or numeric literals, variables, operators, and other expressions, and they can range from simple to quite complex. For example, the following are expressions that use the assignment operator (more on operators in the next section) to assign numerical or string values to variables:
x = 7; str = "Hello, World!";
By contrast, the following is a more complex expression whose final value depends on the values of the quitFlag and formComplete variables:
(quitFlag == TRUE) & (formComplete == FALSE)
Operators do just what their name suggests: They operate on variables or literals. The items that an operator acts on are called its operands. Operators come in the two following types:
Assignment Operators Assignment operators take the result of an expression and assign it to a variable. JavaScript doesn't allow you to assign the result of an expression to a literal. One feature of JavaScript that is not found in most other programming languages is that you can change a variable's type on the fly. Consider the HTML document in Listing 41.1.
Listing 41.1 Var-fly.htm-JavaScript Allows You to Change the Data Type of Variables
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide this script from incompatible Web browsers!
function typedemo() {
var x;
document.writeln("<HR>");
x = Math.PI;
document.writeln("x is " + x + "<BR>");
x = FALSE;
document.writeln("x is " + x + "<BR>");
document.writeln("<HR>");
}
<!-- -->
</SCRIPT>
<TITLE>Changing Data Types on the Fly!</TITLE>
</HEAD>
<BODY BGCOLOR=#FFFFFF>
If your Web browser doesn't support JavaScript, this is all you will see!
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide this script from incompatible Web browsers!
typedemo();
<!-- -->
</SCRIPT>
</BODY>
</HTML>
This short program first prints the (correct) value of pi in the variable x. In most other languages, though, trying to set a floating-point variable to a Boolean value would either generate a compiler error or a runtime error. JavaScript happily accepts the change and prints x's new value: FALSE (see Figure 41.1).
The most common assignment operator, =, simply assigns
the value of an expression's right side to its left side. In the
previous example, the variable x got the integer value
7 after the expression was evaluated. For convenience,
JavaScript also defines some other operators that combine common
math operations with assignment; they're shown in Table 41.1.
| What It Does | Two Equivalent Expressions | |
| Adds two values | x+=y and x=x+y | |
| Adds two strings | string += "HTML" and string = string + "HTML" | |
| Subtracts two values | x-=y and x=x-y | |
| Multiplies two values | a*=b and a=a*b | |
| Divides two values | e/=b and e=e/b |
Math Operators The preceding sections gave you a sneak preview of the math operators that JavaScript furnishes. You can either combine math operations with assignments, as shown in Table 41.1, or use them individually. As you would expect, the standard four math functions (addition, subtraction, multiplication, and division) work just as they do on an ordinary calculator. The negation operator, -, is a unary operator that negates the sign of its operand. Another useful binary math operator is the modulus operator, %. This operator returns the remainder after the integer division of two integer numbers. For instance, in the expression
x = 13%5;
the variable x would be given the value of 3.
JavaScript also adds two useful unary operators: -- and ++, called, respectively, the decrement and increment operators. These two operators modify the value of their operand, and they return the new value. They also share a unique property: They can be used either before or after their operand. If you put the operator after the operand, JavaScript returns the operand's value and then modifies it. If you take the opposite route and put the operator before the operand, JavaScript modifies it and returns the modified value. The following short example might help clarify this seemingly odd behavior:
x = 7; // set x to 7 a = --x; // set x to x-1, and return the new x; a = 6 b = a++; // set b to a, so b = 6, then add 1 to a; a = 7 x++; // add one to x; ignore the returned value
Comparison Operators Comparing the value of two expressions to see whether one is larger, smaller, or equal to another is often necessary. JavaScript supplies several comparison operators that take two operands and return TRUE if the comparison is true and FALSE if it's not. (Remember, you can use literals, variables, or expressions with operators that require expressions.) Table 41.2 shows the JavaScript comparison operators.
Thinking of the comparison operators as questions may be helpful. When you write the following:
(x >= 10)
you're really saying, "Is the value of variable x
greater than or equal to 10?" The return value answers
the question, TRUE or FALSE.
| Read It As | Returns TRUE When | |
| Equals | The two operands are equal | |
| Does not equal | The two operands are unequal | |
| Less than | The left operand is less than the right operand | |
| Less than or equal to | The left operand is less than or equal to the right operand | |
| Greater than | The left operand is greater than the right operand | |
| Greater than or equal to | The left operand is greater than or equal to the right operand |
Logical Operators Comparison operators compare quantity or content for numeric and string expressions, but sometimes you need to test a logical value, like whether a comparison operator returns TRUE or FALSE. JavaScript's logical operators allow you to compare expressions that return logical values. The following are JavaScript's logical operators:
x = TRUE && TRUE; // x is TRUE x = FALSE && FALSE; // x is FALSE x = FALSE && TRUE; // x is FALSE
x = TRUE || TRUE; // x is TRUE x = FALSE || TRUE; // x is TRUE x = FALSE || FALSE; // x is FALSE
Note that the "and" and "or" operators don't evaluate the second operand if the first operand provides enough information for the operator to return a value. This process, called short-circuit evaluation, can be significant when the second operand is a function call. For example,
keepGoing = (userCancelled == FALSE) && (theForm.Submit())
If userCancelled is TRUE, the second operand, which submits the active form, isn't called.
String Operators A few of the operators previously listed can be used for string manipulation, as well. All of the comparison operators can be used on strings, too; the results depend on standard lexicographic ordering, but comparisons aren't case-sensitive. Additionally, the + operator can also be used to concatenate strings. The expression
str = "Hello, " + "World!";
assigns the resulting string Hello, World! to the variable str.
Some scripts you write will be simple; they'll execute the same way every time, once per page. For example, if you add a JavaScript to play a sound when users visit your home page, it doesn't need to evaluate any conditions or do anything more than once. More sophisticated scripts might require that you take different actions under different circumstances. You might also want to repeat the execution of a block of code-perhaps by a set number of times or as long as some condition is TRUE. JavaScript provides constructs for controlling the execution flow of your script based on conditions, as well as repeating a sequence of operations.
Testing Conditions JavaScript provides a single type of control statement for making decisions: the if...else statement. To make a decision, you supply an expression that evaluates to TRUE or FALSE; which code executes depends on what your expression evaluates to.
The simplest form of if...else uses only the if part. If the specified condition is TRUE, the code following the condition is executed; if not, it's skipped. For example, in the following code fragment, the message appears only if the condition (that the lastModified.year property of the document object says it was modified before 1995) is TRUE:
if (document.lastModified.year < 1995)
document.write("Danger! This is a mighty old document.")
You can use any expression as the condition. Since expressions can be nested and combined with the logical operators, your tests can be pretty sophisticated. For example,
if ((document.lastModified.year >= 1995) && (document.lastModified.month >= 10))
document.write("This document is reasonably current.")
The else clause allows you to specify a set of statements to execute when the condition is FALSE, for instance,
if ((document.lastModified.year >= 1995) && (document.lastModified.month >= 10))
document.write("This document is reasonably current.")
else
document.write("This document is quite old.")
Repeating Actions JavaScript provides two different loop constructs that you can use to repeat a set of operations. The first, called a for loop, executes a set of statements some number of times. You specify three expressions: an initial expression that sets the values of any variables you need to use, a condition that tells the loop how to see when it's done, and an increment expression that modifies any variables that need it. Here's a simple example:
for (count=0; count < 100; count++)
document.write("Count is ", count);
This loop executes 100 times and prints out a number each time. The initial expression sets the counter, count, to zero. The condition tests to see whether count is less than 100 and the increment expression increments count.
You can use several statements for any of these expressions, as follows:
for (count=0, numFound = 0; (count < 100) && (numFound < 3); count++) if (someObject.found()) numFound++;
This loop either loops 100 times or as many times as it takes to "find" three items-the loop condition terminates when count >= 100 or when numFound >= 3.
The second form of loop is the while loop. It executes statements as long as its condition is TRUE. For example, you can rewrite the first for loop in the preceding example as follows:
count = 0
while (count < 100) {
if (someObject.found()) numFound++;
document.write("Count is ", count)
}
Which form you use depends on what you're doing; for loops are useful when you want to perform an action a set number of times, and while loops are best when you want to keep doing something as long as a particular condition remains TRUE. Notice that by using braces, you can include more than one command to be executed by the while loop (this is also TRUE of for loops and if...else constructs).
JavaScript reserves some keywords for its own use. You cannot define your own methods or properties with the same name as any of these keywords; if you do, the JavaScript interpreter complains.
JavaScript's reserved keywords are shown in Table 41.3.
| TIP |
Some of these keywords are reserved for future use. JavaScript might allow you to use them, but your scripts may break in the future if you do |
| abstract | double | instanceof | super |
| boolean | else | int | switch |
| break | extends | interface | synchronized |
| byte | FALSE | long | this |
| case | final | native | throw |
| catch | finally | new | throws |
| char | float | null | transient |
| class | for | package | TRUE |
| const | function | private | try |
| continue | goto | protected | var |
| default | if | public | void |
| do | implements | return | while |
| import | short | with | in |
| static |
| CAUTION |
Because JavaScript is still being developed and refined by Netscape, the list of reserved keywords might change or grow over time. Whenever a new version of JavaScript is released, it might be a good idea to look over its new capabilities with an eye towards conflicts with your JavaScript programs |
This section provides a quick reference to some of the other JavaScript commands. The commands are listed in alphabetical order-many have examples. Here's what the formatting of these entries mean:
The break statement The break statement terminates the current while or for loop and transfers program control to the statement following the terminated loop.
Syntax
break
Example
The following function scans the list of URLs in the current document and stops when it has seen all URLs or when it finds an URL that matches the input parameter searchName:
function findURL(searchName) {
var i = 0;
for (i=0; i < document.links.length; i++) {
if (document.links[i] == searchName) {
document.writeln(document.links[i] + "<br>")
break;
}
}
}
The continue statement The continue statement stops executing the statements in a while or for loop, and skips to the next iteration of the loop. It doesn't stop the loop altogether like the break statement; instead, in a while loop, it jumps back to the condition, and in a for loop, it jumps to the update expression.
Syntax
continue
Example
The following function prints the odd numbers between 1 and x; it has a continue statement that goes to the next iteration when i is even:
function printOddNumbers(x) {
var i = 0
while (i < x) {
i++;
if ((i % 2) == 0) // the % operator divides & returns the remainder
continue
else
document.write(i, "\n")
}
}
The for loop A for loop consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a block of statements executed in the loop. These parts do the following:
Syntax
for ([initial_expr;] [condition;] [update_expr]) {
statements
}
Example
This simple for statement prints out the numbers from 0 to 9. It starts by declaring a loop counter variable, i, and initializing it to zero. As long as i is less than 9, the update expression increments i, and the statements in the loop body execute.
for (var i = 0; i <= 9; i++) {
document.write(i);
}
The for...in loop The for...in loop is a special form of the for loop that iterates the variable variable-name over all the properties of the object named object-name. For each distinct property, it executes the statements in the loop body.
Syntax
for (var in obj) {
statements
}
Example
The following function takes as its arguments an object and the object's name. It then uses the for...in loop to iterate through all the object's properties and writes them into the current Web page.
function dump_props(obj,obj_name) {
for (i in obj)
document.writeln(obj_name + "." + i + " = " + obj[i] + "<br>");
}
The function statement The function statement declares a JavaScript function; the function may optionally accept one or more parameters. To return a value, the function must have a return statement that specifies the value to return. All parameters are passed to functions by value-the function gets the value of the parameter but cannot change the original value in the caller.
Syntax
function name([param] [, param] [..., param]) {
statements
}
Example
function PageNameMatches(theString) {
return (document.title == theString)
}
The if...else statement The if...else statement is a conditional statement that executes the statements in block1 if condition is TRUE. In the optional else clause, it executes the statements in block2 if condition is FALSE. The blocks of statements can contain any JavaScript statements, including further nested if statements.
Syntax
if (condition) {
statements
}
[else {
statements}]
Example
if (Message.IsEncrypted()) {
Message.Decrypt(SecretKey);
}
else {
Message.Display();
}
The new statement The new statement is the way that new objects are created in JavaScript. For instance, if you defined the following function to create a house object
function house (rms,stl,yr,garp) { // define a house object
this.room = rms; // number of rooms (integer)
this.style = stl; // style (string)
this.yearBuilt = yr; // year built (integer)
this.hasGarage = garp; // has garage? (boolean)
}
you could then create an instance of a house object using the new statement, as in the following:
var myhouse = new house(3,"Tenement",1962,false);
A few notes about this example. First, note that the function used to create the object doesn't actually return a value. The reason it is able to work is that it makes use of the this object, which always refers to the current object. Second, whereas the function defines how to create the house object, none is actually created until the function is called using the new statement.
The return statement The return statement specifies the value to be returned by a function.
Syntax
return expression;
Example
The following simple function returns the square of its argument, x, where x is any number.
function square( x ) {
return x * x;
}
The this statement You use this to access methods or properties of an object within the object's methods. The this statement always refers to the current object.
Syntax
this.property
Example
If setSize is a method of the document object, then this refers to the specific object whose setSize method is called:
function setSize(x,y) {
this.horizSize = x;
this.vertSize = y;
}
This method sets the size for an object when called as follows:
document.setSize(640,480);
The var statement The var statement declares a variable varname, optionally initializing it to have value. The variable name varname can be any JavaScript identifier, and value can be any legal expression (including literals).
Syntax
var varname [= value] [, var varname [= value] ] [..., var varname [= value] ]
Example
var num_hits = 0, var cust_no = 0;
The while statement The while statement contains a condition and a block of statements. The while statement evaluates the condition; if condition is TRUE, it executes the statements in the loop body. It then reevaluates condition and continues to execute the statement block as long as condition is TRUE. When condition evaluates to FALSE, execution continues with the next statement following the block.
Syntax
while (condition) {
statements
}
Example
The following simple while loop iterates until it finds a form in the current document object whose name is "OrderForm" or until it runs out of forms in the document:
x = 0;
while ((x < document.forms[].length) && (document.forms[x].name
!= "OrderForm")) {
x++
}
The with statement The with statement establishes object as the default object for the statements in block. Any property references without an object are then assumed to be for object.
Syntax
with object {
statements
}
Example
with document {
write "Inside a with block, you don't need to specify the object.";
bgColor = gray;
}
The most important thing you will be doing with your JavaScripts is interacting with the content and information on your Web pages, and through it, with your user. JavaScript interacts with your Web browser through the browser's object model. Different aspects of the Web browser exist as different objects, with properties and methods that can be accessed by JavaScript. For instance, document.write() uses the write method of the document object. Understanding this Web browser object model is crucial to using JavaScript effectively. Understanding how the Web browser processes and executes your scripts is also necessary.
When you put JavaScript code in a page, the Web browser evaluates the code as soon as it's encountered. Functions, however, don't execute when they're evaluated; they just get stored for later use. You still have to call functions explicitly to make them work. Some functions are attached to objects, such as buttons or text fields on forms, and they are called when some event happens on the button or field. You might also have functions that you want to execute during page evaluation. You can do so by putting a call to the function at the appropriate place in the page.
You can put scripts anywhere within your HTML page as long as they're surrounded with the <SCRIPT>...</SCRIPT> tags. One good system is to put functions that execute more than once into the <HEAD> element of their pages; this element provides a convenient storage place. Because the <HEAD> element is at the beginning of the file, functions and JavaScript code that you put there will be evaluated before the rest of the document is loaded. Then you can execute the function at the appropriate point in your Web page by calling it, as in the following:
<SCRIPT language="JavaScript"> <!-- Hide this script from incompatible Web browsers! myFunction(); <!-- --> </SCRIPT>
Another way to execute scripts is to attach them to HTML elements that support scripts. When scripts are matched with events attached to these elements, the script is executed when the event occurs. This can be done with HTML elements, such as forms, buttons, or links. Consider Listing 41.2, which shows a very simple example of attaching a JavaScript function to the onClick attribute of an HTML form button (see Figure 41.2).
Figure 41.2 : JavaScript functions can be attached to form fields through several different methods.
Listing 41.2 Button1.htm-Calling a JavaScript Function with the Click of a Button
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide this script from incompatible Web browsers!
function pressed() {
alert("I said Don't Press Me!");
}
<!-- -->
</SCRIPT>
<TITLE>JavaScripts Attached to HTML Elements</TITLE>
</HEAD>
<BODY BGCOLOR=#ffffff>
<FORM NAME="Form1">
<INPUT TYPE="button" NAME="Button1" VALUE="Don't Press Me!"
onClick="pressed()">
</FORM>
</BODY>
</HTML>
JavaScript also provides you with an alternate way to attach functions to objects and their events. For simple actions, you can attach the JavaScript directly to the attribute of the HTML form element, as shown in Listing 41.3. Each of these listings will produce the output shown in Figure 41.2.
Listing 41.3 Button2.htm-Simple JavaScripts Can Be Attached Right to a Form Element
<HTML>
<HEAD>
<TITLE>JavaScripts Attached to HTML Elements</TITLE>
</HEAD>
<BODY BGCOLOR=#FFFFFF>
<FORM NAME="Form1">
<INPUT TYPE="button" NAME="Button1" VALUE="Don't Press Me!"
onClick="alert('I said Don\'t Press Me!')">
</FORM>
</BODY>
</HTML>
Sometimes, though, you have code that shouldn't be evaluated or
execute until after all the page's HTML has been parsed and displayed.
An example would be a function to print out all the URLs referenced
in the page. If this function is evaluated before all the HTML
on the page has been loaded, it misses some URLs, so the call
to the function should come at the end of the page. The function
itself can be defined anywhere in the HTML document; it is the
function call that should be at the end of the page.
| NOTE |
JavaScript code to modify the actual HTML contents of a document (as opposed to merely changing the text in a form text input field, for instance) must execute during page evaluation |
In addition to recognizing JavaScript when it's embedded inside a <SCRIPT> tag, compatible Web browsers also expose some objects (and their methods and properties) that you can use in your JavaScript programs. They can also trigger methods you define when the user takes certain actions in the browser.
Figure 41.3 shows the hierarchy of objects that the Web browser provides and that are accessible to JavaScript. As shown, window is the topmost object in the hierarchy, and the other objects are organized underneath it as shown. Using this hierarchy, the full reference for the value of a text field named text1 in an HTML form named form1 would be
window.document.form1.text1.value
However, because of the object scoping rules in JavaScript, it is not necessary to specify this full reference. Scoping refers to the range over which a variable, function, or object is defined. For instance, a variable defined within a JavaScript function is scoped only within that function-it cannot be referenced outside of the function. JavaScripts are scoped to the current window but not to the objects below the window in the hierarchy. So for the preceding example, the text field value could also be referenced as document.form1.text1.value.
Many events that happen in a Web browsing session aren't related to items on the page, such as buttons or HTML text. Instead, they're related to what's happening in the browser itself, such as what page the user is viewing.
The location Object Internet Explorer 3 exposes
an object called location, which holds the current URL,
including the hostname, path, CGI script arguments, and even the
protocol. Table 41.4 shows the properties and methods of the location
object.
| Property | Type | What It Does |
| href | String | Contains the entire URL, including all the subparts; for example, http://www.msn.com/products/msprod.htm |
| protocol | String | Contains the protocol field of the URL, including the first colon; for example, http: |
| host | String | Contains the hostname and port number; for example, www.msn.com:80 |
| hostname | String | Contains only the hostname; for example, www.msn.com |
| port | String | Contains the port if specified; otherwise, it's blank |
| path | String | Contains the path to the actual document; for example, products/msprod.htm |
| hash | String | Contains any CGI arguments after the first # in the URL |
| search | String | Contains any CGI arguments after the first ? in the URL |
| toString() | Method | Returns location.href; you can use this function to easily get the entire URL |
| assign(x) | Method | Sets location.href to the value you specify |
Listing 41.4 shows an example of how you access and use the location object. First, the current values of the location properties are displayed on the Web page (see Figure 41.4). As you can see, not all of them are defined. Additionally, when the button is clicked, the location.href property is set to the URL of my home page. This causes the Web browser to load that page (see Figure 41.5).
Listing 41.4 Loc-props.htm-The location Object Allows You to Access and Set Information About the Current URL
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide this script from incompatible Web browsers!
function gohome() {
location.href = "http://www.rpi.edu/~odonnj/";
}
<!-- -->
</SCRIPT>
<TITLE>The Location Object</TITLE>
</HEAD>
<BODY BGCOLOR=#FFFFFF>
<SCRIPT LANGUAGE="Javascript">
<!-- Hide this script from incompatible Web browsers!
document.writeln("Current location information: <BR> <HR>");
document.writeln("location.href = " + location.href + "<BR>");
document.writeln("location.protocol = " + location.protocol + "<BR>");
document.writeln("location.host = " + location.host + "<BR>");
document.writeln("location.hostname = " + location.hostname + "<BR>");
document.writeln("location.port = " + location.port + "<BR>");
document.writeln("location.pathname = " + location.pathname + "<BR>");
document.writeln("location.hash = " + location.hash + "<BR>");
document.writeln("location.search = " + location.search + "<BR> <HR>");
<!-- -->
</SCRIPT>
<FORM NAME="Form1">
<INPUT TYPE="button" NAME="Button1" VALUE="Goto JOD's Home Page!"
onClick="gohome()">
</FORM>
</BODY>
</HTML>
The document Object Web browsers also expose an object called document; as you might expect, this object exposes useful properties and methods of the active document. The location object refers only to the URL of the active document, but document refers to the document itself. Table 41.5 shows document's properties and methods.
The history Object The Web browser also maintains
a list of pages you've visited since running the program; this
list is called the history list and can be accessed through
the history object. Your JavaScript programs can move
through pages in the list using the properties and functions shown
in Table 41.6.
| Property | Type | What It Does |
| title | String | Contains title of the current page or Untitled if there's no title. |
| URL or Location | String | Contain the document's address (from its Location history stack entry); these two are synonyms. |
| lastModified | String | Contains the page's last-modified date. |
| forms[] | Array | Contains all the FORMs in the current page. |
| forms[].length | Integer | Contains the number of FORMs in the current page. |
| links[] | Array | Contains all HREF anchors in the current page. |
| links[].length | Integer | Contains the number of HREF anchors in the current page. |
| write(x) | Method | Writes HTML to the current document, in the order in which the script occurs on the page. |
| Property | Type | What It Does |
| previous or back | String | Contains the URL of the previous history stack entry (that is, the one before the active page). These properties are synonyms. |
| next or forward | String | Contains the URL of the next history stack entry (that is, the one after the active page). These properties are synonyms. |
| go(x) | Method | Goes forward x entries in the history stack if x > 0; otherwise, goes backward x entries. x must be a number. |
| go(str) | Method | Goes to the newest history entry whose title or URL contains str as a substring; the string case doesn't matter. str must be a string. |
The window Object The Web browser creates a window object for every document. Think of the window object as an actual window, and the document object as the content that appears in the window. The following are a couple of the methods available for working in the window:
The form Object There are a series of object, properties, methods, and events associated with HTML forms when used in a Web page. Some of them you have already seen in the examples presented thus far in this chapter, and they are more fully described in Chapter 48, "ActiveX Scripting: VB Script and JScript." All of the properties of the form object described in that chapter work the same way in JavaScript as in VB Script. Additionally, a JavaScript version of the VB Script sample intranet application, which uses HTML forms extensively, is located on the CD-ROMs that accompany this book.
In this section, you'll see a couple of examples of JavaScript applications. A common example scripting application generally involves interaction with HTML forms to perform client-side validation of the forms data before submission. JavaScript can perform this function very well. If you are interested in seeing an example of using JavaScript in this way, read the description of the VB Script intranet application in Chapter 48, which contains a note that refers you to the place on the CD-ROM where you can find a JavaScript version that does much the same thing.
In order to not duplicate the forms discussion, the example shown in this chapter will show how JavaScript can be used within a Web browser to interact with browser frames and windows. As usual, the interface between the user and the JavaScript code remains HTML forms elements. The examples also show you how to open, close, and manipulate Web browser windows and frames.
This example shows how it is possible to create an HTML forms-based control panel that uses JavaScript to load and execute other JavaScripts in their own windows. This is done through the use of the window Web browser object, its properties, and its methods.
Listing 41.5 shows the "main program," the top-level HTML document giving access to the control panel (see Figure 41.6). The JavaScript in this example is very simple and is included in the onClick attribute of the form's <input> tag. Clicking the button executes the JavaScript open window method:
Figure 41.6 : The Control Panel button calls a JavaScript and creates a new browser window.
window.open('cp.htm','ControlPanel','width=300,height=250')
This creates a window named ControlPanel that is 300´250 pixels in size and loads the HTML document Cp.htm.
Listing 41.5 Cpmain.htm-A JavaScript Attached Right to a Form Button Creates a New Window When Clicked
<HTML>
<HEAD>
<TITLE>JavaScript Window Example</TITLE>
</HEAD>
<BODY BGCOLOR=#FFFFFF>
<CENTER><H3>Activate the control panel by clicking below</H3></CENTER>
<HR>
<FORM>
<CENTER>
<TABLE>
<TR><TD><INPUT TYPE="button" NAME="ControlButton" VALUE="Control Panel"
onClick="window.open('cp.htm','ControlPanel',
'width=300,height=250')"></TD></TR>
</TABLE>
</CENTER>
</FORM>
</BODY>
</HTML>
When the button is clicked, Cp.htm is loaded into its own window, as shown in Figure 41.7 (note that in Figures 41.7 and 41.8, the windows have been manually rearranged so that they all can be seen). This HTML document uses an interface of an HTML form organized in a table to give access through this control panel to other JavaScript applications, namely a timer and a real-time clock. Listing 41.6 shows Cp.htm. The JavaScript openTimer(), openClock(), closeTimer(), and closeClock() functions are used to open and close windows for a JavaScript timer and clock, respectively. These functions are attached to form buttons that make up the control panel. Note that the JavaScript timerw and clockw variables, because they are defined outside of any of the functions, can be used anywhere in the JavaScript document. They are used to remember whether or not the timer and clock windows are opened.
Figure 41.7 : JavaScript can create new Web browser windows with definable widths and heights.
Listing 41.6 Cp.htm-This HTML Form Calls JavaScripts to Create and Destroy Windows for a Timer and a Real-Time Clock
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide this script from incompatible Web browsers!
var timerw = null;
var clockw = null;
function openTimer() {
if(!timerw)
timerw = open("cptimer.htm","TimerWindow","width=300,height=100");
}
function openClock() {
if(!clockw)
clockw = open("cpclock.htm","ClockWindow","width=50,height=25");
}
function closeTimer() {
if(timerw) {
timerw.close();
timerw = null;
}
}
function closeClock() {
if(clockw) {
clockw.close();
clockw = null;
}
}
<!-- -->
</SCRIPT>
</HEAD>
<BODY BGCOLOR=#EEEEEE>
<FORM>
<CENTER>
<TABLE>
<TR><TD>To Open Timer...</TD>
<TD ALIGN=CENTER>
<INPUT TYPE="button" NAME="ControlButton" VALUE="Click Here!"
onClick="openTimer()"></TD></TR>
<TR><TD>To Close Timer...</TD>
<TD ALIGN=CENTER>
<INPUT TYPE="button" NAME="ControlButton" VALUE="Click Here!"
onClick="closeTimer()"></TD></TR>
<TR><TD>To Open Clock...</TD>
<TD ALIGN=CENTER>
<INPUT TYPE="button" NAME="ControlButton" VALUE="Click Here!"
onClick="openClock()"></TD></TR>
<TR><TD>To Close Clock...</TD>
<TD ALIGN=CENTER>
<INPUT TYPE="button" NAME="ControlButton" VALUE="Click Here!"
onClick="closeClock()"></TD></TR>
<TR><TD>To Open Both...</TD>
<TD ALIGN=CENTER>
<INPUT TYPE="button" NAME="ControlButton" VALUE="Click Here!"
onClick="openTimer();openClock();"></TD></TR>
<TR><TD>To Close Both...</TD>
<TD ALIGN=CENTER>
<INPUT TYPE="button" NAME="ControlButton" VALUE="Click Here!"
onClick="closeTimer();closeClock();"></TD></TR>
<TR><TD></TD></TR>
<TR><TD>To Close Everything...</TD>
<TD ALIGN=CENTER>
<INPUT TYPE="button" NAME="ControlButton" VALUE="Click Here!"
onClick="closeTimer();closeClock();self.close();"></TD></TR>
</TABLE>
</CENTER>
</FORM>
</BODY>
</HTML>
Listings 41.7 and 41.8 show Cptimer.htm and Cpclock.htm, the HTML documents to implement the JavaScript timer and real-time clock. Note that each uses the properties of the JavaScript Date object to access time information. Figure 41.8 shows the Web page with the control panel, timer, and real-time clock windows all open.
Listing 41.7 Cptimer.htm-The JavaScript Date Object Can Be Used to Keep Track of Relative Time
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide this script from incompatible Web browsers!
var timerID = 0;
var tStart = null;
function UpdateTimer() {
if(timerID) {
clearTimeout(timerID);
clockID = 0;
}
if(!tStart)
tStart = new Date();
var tDate = new Date();
var tDiff = tDate.getTime() - tStart.getTime();
var str;
tDate.setTime(tDiff);
str = ""
if (tDate.getMinutes() < 10)
str += "0" + tDate.getMinutes() + ":";
else
str += tDate.getMinutes() + ":";
if (tDate.getSeconds() < 10)
str += "0" + tDate.getSeconds();
else
str += tDate.getSeconds();
document.theTimer.theTime.value = str;
timerID = setTimeout("UpdateTimer()", 1000);
}
function Start() {
tStart = new Date();
document.theTimer.theTime.value = "00:00";
timerID = setTimeout("UpdateTimer()", 1000);
}
function Stop() {
if(timerID) {
clearTimeout(timerID);
timerID = 0;
}
tStart = null;
}
function Reset() {
tStart = null;
document.theTimer.theTime.value = "00:00";
}
<!-- -->
</SCRIPT>
</HEAD>
<BODY BGCOLOR=#AAAAAA onload="Reset();Start()" onunload="Stop()">
<FORM NAME="theTimer">
<CENTER>
<TABLE>
<TR><TD COLSPAN=3 ALIGN=CENTER>
<INPUT TYPE=TEXT NAME="theTime" SIZE=5></TD></TR>
<TR><TD></TD></TR>
<TR><TD><INPUT TYPE=BUTTON NAME="start" VALUE="Start"
onclick="Start()"></TD>
<TD><INPUT TYPE=BUTTON NAME="stop" VALUE="Stop"
onclick="Stop()"></TD>
<TD><INPUT TYPE=BUTTON NAME="reset" VALUE="Reset"
onclick="Reset()"></TD>
</TR>
</TABLE>
</CENTER>
</FORM>
</BODY>
</HTML>
Listing 41.8 Cpclock.htm-The Date Object Can Also Be Used to Access the Real-Time Clock of the Client System
<HTML>
<HEAD>
<TITLE>Clock</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide this script from incompatible Web browsers!
var clockID = 0;
function UpdateClock() {
if(clockID) {
clearTimeout(clockID);
clockID = 0;
}
var tDate = new Date();
var str;
str = "";
if (tDate.getHours() < 10)
str += "0" + tDate.getHours() + ":";
else
str += tDate.getHours() + ":";
if (tDate.getMinutes() < 10)
str += "0" + tDate.getMinutes() + ":";
else
str += tDate.getMinutes() + ":";
if (tDate.getSeconds() < 10)
str += "0" + tDate.getSeconds();
else
str += tDate.getSeconds();
document.theClock.theTime.value = str;
clockID = setTimeout("UpdateClock()", 1000);
}
function StartClock() {
clockID = setTimeout("UpdateClock()", 500);
}
function KillClock() {
if(clockID) {
clearTimeout(clockID);
clockID = 0;
}
}
<!-- -->
</SCRIPT>
</HEAD>
<BODY BGCOLOR=#CCCCCC onload="StartClock()" onunload="KillClock()">
<CENTER>
<FORM NAME="theClock">
<INPUT TYPE=TEXT NAME="theTime" SIZE=8>
</FORM>
</CENTER>
</BODY>
</HTML>
In this example, you can see further examples of window manipulation using JavaScript-in addition, you will see how different frames can be accessed and manipulated. Listing 41.9 shows Wfmain.htm. Like Cpmain.htm in the previous example, this is the simple, top-level HTML document for this example. This one is even simpler in that it doesn't contain any JavaScript at all, simply setting up the frameset and frames for the example and indicating the HTML documents, Wftop.htm and Wftext.htm, to be loaded into each frame.
Listing 41.9 Wfmain.htm-This Main HTML Document Creates a Frameset and Loads Two Other Documents into the Resulting Frames
<HTML> <TITLE>Windows and Frames</TITLE> <FRAMESET ROWS="100,*"> <FRAME SRC="wftop.htm" NAME="frame1" SCROLLING="no" NORESIZE> <FRAME SRC="wftext.htm" NAME="frame2"> </FRAMESET> <NOFRAMES> </NOFRAMES> </HTML>
The document that makes up the upper frame, shown in Listing 41.10, creates a button bar of functions that can be used to manipulate the frames and windows of this example. The initial contents of the lower frame give some quick instructions on what each button does (see Listing 41.11). The resulting Web page, when this is loaded into a Web browser, is shown in Figure 41.9.
Listing 41.10 Wftop.htm-The HTML and JavaScripts in this Web Page Allow the Manipulation of the Windows and Frames in This Example
<HTML>
<HEAD>
<TITLE>Windows and Frames</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide this script from incompatible Web browsers!
function bottomColor(newColor) {
window.parent.frames['frame2'].document.bgColor=newColor;
}
function topColor(newColor) {
window.parent.frames['frame1'].document.bgColor=newColor;
}
function navi() {
window.open('wfvisit.htm','Visit',
'toolbar=no,location=no,directories=no,' +
'status=no,menubar=no,scrollbars=no,resizable=no,' +
'copyhistory=yes,width=600,height=200');
}
function Customize() {
var PopWindow=window.open('wfcolor.htm','Main',
'toolbar=no,location=no,directories=no,status=no,' +
'menubar=no,scrollbars=no,resizable=no,copyhistory=yes,' +
'width=400,height=200');
PopWindow.creator = self;
}
function ConfirmClose() {
if (confirm("Are you sure you wish to exit Netscape?"))
window.close()
}
<!-- -->
</SCRIPT>
</HEAD>
<BODY>
<CENTER>
<FONT COLOR=RED>
<H2>Windows and Frames</H2>
<FORM>
<INPUT TYPE="BUTTON" VALUE="Back"
onClick="parent.frame2.history.back()">
<INPUT TYPE="BUTTON" VALUE="Visit Other Sites"
onClick="navi()">
<INPUT TYPE="BUTTON" VALUE="Background Colors"
onClick="Customize()">
<INPUT TYPE="BUTTON" VALUE="Forward"
onClick="parent.frame2.history.forward()">
<INPUT TYPE="BUTTON" VALUE="Exit"
onClick="ConfirmClose()">
</CENTER>
</FORM>
</BODY>
</HTML>
Listing 41.11 Wftext.htm-This Informational Web Page Also Provides the Jumping-Off Point to Another Site
<HTML>
<HEAD>
<TITLE>Windows and Frames Text</TITLE>
</HEAD>
<BODY BGCOLOR=#FFFFFF>
<CENTER>
<H2>Welcome to Windows and Frames Using JavaScript</H2>
</CENTER>
<B>There are 5 control buttons on the control panel:<BR>
<OL><LI>Forward: Takes you to the front of the frame. (This only works
after you actually choose to go somewhere and come back.)
<LI>Visit Other Site: This window will let you type a site address and
you will be able to visit that specific site.
<LI>Background Color: Lets you choose the top and the bottom frame's
background color.
<LI>Back: Takes you back on a frame.
<LI>Exit: Exits from Netscape.
</OL>
</B>
<CENTER>
Let's check the "back/forward" buttons. Let's<BR>
<FONT SIZE="+2"><A HREF="http://www.microsoft.com">Go Somewhere!!!</A>
</BODY>
</HTML>
The intent of this example is to use the button bar and attached JavaScript functions off the top frame to manipulate the contents of the lower frame, and the appearance of both. If you follow instructions and click the "Go Somewhere!!!" hypertext link in the lower frame, the URL included in the listing for that link (the Microsoft home page) is loaded into the lower frame (see Figure 41.10).
By using a JavaScript function navi(), the Visit Other Sites button creates a window and loads in the HTML document Wfvisit.htm, shown in Listing 41.12. This document uses an HTML form to query the user for an URL (see Figure 41.11) and then makes use of the Web browser frame object to load the Web page referenced by that URL into the lower frame (see Figure 41.12).
Listing 41.12 Wfvisit.htm-The HTML and JavaScript in This File Allow Other Web Pages to Be Loaded into the Lower Frame
<HTML>
<HEAD>
<TITLE>Windows and Frames Navigator</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide this script from incompatible Web browsers!
function visit(frame) {
if (frame == "frame2")
open(document.getsite.site.value,frame);
return 0;
}
<!-- -->
</SCRIPT>
</HEAD>
<BODY BGCOLOR=#FFFFFF>
<CENTER>
<H2><B>Windows and Frames Navigator</B></H2>
<FORM NAME="getsite" METHOD="post">
<hR>
<INPUT TYPE="TEXT" NAME="site" SIZE=50>
<INPUT TYPE="BUTTON" NAME="gobut" VALUE="Go!"
onclick="window.close();visit('frame2')">
<HR>
<INPUT TYPE="BUTTON" VALUE="Exit" onclick="window.close()">
</FORM>
</BODY>
</HTML>
The Back and Forward buttons also call JavaScript functions that use the frame object to move the lower frame backward and forward through its history list.
Anther capability given by the upper frame toolbar is the ability to specify the background colors of either the upper or lower frame. Clicking the Background Colors button creates a window and loads the HTML document shown in Listing 41.13. This window uses HTML form radio buttons to allow you to select from five choices of background color for each frame. Note that the creator object and topColor() and bottomColor() methods used in Listing 41.13 to change the frame colors are set up in the Customize() function of the Wftop.htm HTML document (see Listing 41.10). Because this window is created by that function, it inherits those objects and methods and can use them to change the frame background colors (see Figure 41.13).
Listing 41.13 Wfcolor.htm-JavaScript Allows You to Manipulate the Appearance of Windows and Frames that Are Being Viewed
<HTML>
<HEAD>
<TITLE>Windows and Frames Custom Colors</TITLE>
</HEAD>
<CENTER>
1. <FONT COLOR="#000000">Black</FONT>
2. <FONT COLOR="#FF0235">Red</FONT>
3. <FONT COLOR="#6600BA">Purple</FONT>
4. <FONT COLOR="#3300CC">Blue</FONT>
5. <FONT COLOR="#FFFFFF">White</FONT>
<FORM NAME="background">
<FONT SIZE=4>
Top Frame Colors<br>
<INPUT TYPE="RADIO" NAME="bgcolor"
onClick="creator.topColor('#000000')">1
<INPUT TYPE="RADIO" NAME="bgcolor"
onClick="creator.topColor('#FF0235')">2
<INPUT TYPE="RADIO" NAME="bgcolor"
onClick="creator.topColor('#6600BA')">3
<INPUT TYPE="RADIO" NAME="bgcolor"
onClick="creator.topColor('#3300CC')">4
<INPUT TYPE="RADIO" NAME="bgcolor"
onClick="creator.topColor('#ffffff')">5
<BR>
Bottom Frame<BR>
<INPUT TYPE="RADIO" NAME="bgcolor"
onClick="creator.bottomColor('#000000')">1
<INPUT TYPE="RADIO" NAME="bgcolor"
onClick="creator.bottomColor('#FF0235')">2
<INPUT TYPE="RADIO" NAME="bgcolor"
onClick="creator.bottomColor('#6600BA')">3
<INPUT TYPE="RADIO" NAME="bgcolor"
onClick="creator.bottomColor('#3300CC')">4
<INPUT TYPE="RADIO" NAME="bgcolor"
onClick="creator.bottomColor('#FFFFFF')">5
<P>
<INPUT TYPE="BUTTON" VALUE="Exit" onClick="window.close()">
</FONT>
</FORM>
</CENTER>
</BODY>
</HTML>
The final button of the upper frame toolbar calls a JavaScript function that gives the user the ability to exit from the Web browser, after first getting confirmation (see Figure 41.14).
Figure 41.14 : The upper frame's Exit button includes a JavaScript confirmation dialog box.