One of JavaScript's strengths is the capability of working with elements of the Web page directly. This is handled through the JavaScript object hierarchy. This hierarchy includes a variety of objects that represent data on the current Web page and in the current browser window.
These objects are organized into a hierarchy of parent and child objects. A child object is simply an object that is used as a property of another object (the parent object).
Each of the objects in the hierarchy includes properties, which are often objects in themselves. It may also include methods to perform functions on the object. Finally, it may include event handlers, which call functions or JavaScript statements when an event happens to that object.
A diagram of the object hierarchy is given in Figure 5.1. The hierarchy begins with the window object, which serves as the parent object for most of the other objects. This chapter describes each object in the following sections, beginning with the window object and working downward through the hierarchy.
Figure 5.1 : The JavaScript object hierarchy.
The window object is at the top of the object hierarchy. A window object exists for each open browser window. The properties of this object describe the document in the window and provide information about the window. Three of the window object's properties are child objects:
Each of these objects is described in detail later in this chapter. In most cases, there is only one window object, so you can omit the window object name when referring to the current script's window. For example, this statement sets the current window's status property:
status = "This is a test."
There are several terms that refer to window objects:
You will now take a closer look at the properties, methods, and event handlers of the window object. The child objects (location, document, and history) will be covered in their own sections later in this chapter.
The window object has a variety of properties that specify information about the window and its components. The simplest property is the name property; this contains the name of the current window.
If you create a window yourself, using the open() method described later in this chapter, you give it a name; otherwise, the name property remains blank. You will now look at the other properties of the window object, which enable you to deal with the status line and with framed documents.
One of the simplest window object properties enables you to manipulate the status line-the gray-background line at the bottom of the window. This line is usually used to display URLs of links as you move the mouse over them. With JavaScript, you can display anything you like in this area.
As an example, Listing 5.1 shows an HTML page that uses a JavaScript event handler to enable you to modify the status line when you press a button.
Listing 5.1. (STATUS.htm) An HTML document that uses JavaScript to change the status line.
<HTML> <HEAD><TITLE>The Amazing Status Line Changer</TITLE> </HEAD> <BODY> <H1>Change the Status Line</H1> <HR> Enter the text for the status line in the space below, then press the chANGE button to change it.<HR> <FORM NAME="statform"> <INPUT TYPE="text" SIZE="65" NAME="input1"><BR> <INPUT TYPE="button" VALUE="chANGE" onClick="window.status=document.statform.input1.value;"> </FORM> <HR> end. </BODY> </HTML>
This is an example of how much you can do with a single JavaScript statement. The HTML defines a form called statform with two fields: a text field and a button. You enter the text in the text field. Each time you press the button, the onClick event handler changes the status line to match the text field. Netscape's display of this page, including a modified status line, is shown in Figure 5.2.
Figure 5.2 : The status line changing program, as displayed
by Netscape.
Note |
Notice the syntax used to refer to the text field: document.statform.input1.value. This may be a bit confusing, but this is the syntax required to access an element of a form. You'll learn about forms in detail in Chapter 6 "Using Interactive Forms." |
Although this application is an example of how much fun you can have with JavaScript in only one statement, it's not very useful. A more common (and more practical) application is to use the status line for onMouseOver event handlers, which enables you to provide useful instructions for links and form elements. You'll learn about this use of the status property in Chapter 8.
Some browsers (including the latest Netscape and Microsoft browsers) support frames or framesets. These enable you to divide the browser window into multiple panes, called frames. Each frame can contain a separate URL or the output of a script.
When you use frames, there are several window objects: one for the main (parent) window, and one for each frame. The window object has two properties that are used with frame documents:
Because frames can make for some complicated-and useful-programming, they are described in detail in Chapter 9 "Using Frames, Cookies, and Other Advanced Features."
Along with the properties you have already looked at, the window object includes a variety of methods. These enable you to perform window-related functions: opening, closing, and manipulating windows and displaying dialog boxes. Methods are also included to set timers to perform an action after a certain time.
The window.open() method enables you to open a new browser window. A typical statement to open a new window looks like this:
WindowName=window.open("URL", "WindowName", "Feature List");
The following are the components of the window.open() statement:
The features available in the third parameter of the window.open() method include width and height, to set the size of the window, and several features that can be set to either yes (1) or no (0): toolbar, location, directories, status, menubar, scrollbars, and resizable. You can list only the features you want to change from the default. This example creates a small window with no toolbar or status line:
SmallWin = window.open("","small","width=100,height=120,toolbar=0,status=0");
Of course, you can close windows as well. The window.close() method closes a window. Netscape doesn't enable you to close the main browser window without the user's permission; its main purpose is for closing windows you have created. For example, this statement closes a window called updatewindow:
updatewindow.close();
As another example, Listing 5.2 shows an HTML document that enables you to open a new window by pressing a button. (I have specified a very small size for the second window so you can tell them apart.) You can then press another button to close the new window. The third button attempts to close the current window; Netscape allows this, but asks for confirmation first.
Listing 5.2. (WINDOWS.htm) An HTML document that uses JavaScript to enable you to create and close windows.
<HTML> <HEAD><TITLE>Create a New Window</TITLE> </HEAD> <BODY> <H1>Create a New Window</H1> <HR> Use the buttons below to test opening and closing windows in JavaScript. <HR> <FORM NAME="winform"> <INPUT TYPE="button" VALUE="Open New Window" onClick="NewWin=window.open('','NewWin', 'toolbar=no,status=no,width=200,height=100'); "> <P><INPUT TYPE="button" VALUE="Close New Window" onClick="NewWin.close();" > <P><INPUT TYPE="button" VALUE="Close Main Window" onClick="window.close();"> </FORM> <BR>Have fun! <HR> </BODY> </HTML>
Again, this example uses event handlers to do its work, one for each of the buttons. Figure 5.3 shows Netscape's display of this page, with the small new window on top.
Figure 5.3 : A new Netscape window opened with JavaScript.
The window object includes three methods that are useful for displaying messages and interacting with the user:
Figure 5.4 : A JavaScript alert dialog displays a message.
Figure 5.5 : A JavaScript confirm dialog asks for confirmation.
As a further illustration of these types of dialogs, Listing 5.3 lists an HTML document that uses buttons and event handlers to enable you to test dialogs.
Listing 5.3. (DIALOG.htm) An HTML document that uses JavaScript to display alerts, confirmations, and prompts.
<HTML> <HEAD><TITLE>Alerts, Confirmations, and Prompts</TITLE> </HEAD> <BODY> <H1>Alerts, Confirmations, and Prompts</H1> <HR> Use the buttons below to test dialogs in JavaScript. <HR> <FORM NAME="winform"> <INPUT TYPE="button" VALUE="Display an Alert" onClick="window.alert('This is a test alert.'); "> <P><INPUT TYPE="button" VALUE="Display a Confirmation" onClick="temp = window.confirm('Would you like to confirm?'); window.status=(temp)?'confirm: true':'confirm: false'; "> <P><INPUT TYPE="button" VALUE="Display a Prompt" onClick="var temp = window.prompt('Enter some Text:','This is the default value'); window.status=temp; "> </FORM> <BR>Have fun! <HR> </BODY> </HTML>
This example displays three buttons, and each uses an event handler to display one of the dialogs. Let's take a detailed look at each one:
Figure 5.6 shows the program in Listing 5.3 in action. The prompt dialog is currently displayed and shows the default value, and the status line is still displaying the result of a previous confirmation dialog.
Figure 5.6 : The dialog box example's output, including
a prompt dialog.
Note |
Notice that Netscape prefaces each of the dialogs with a message, such as "JavaScript Alert:" or "JavaScript Confirm:". Unfortunately, there is no way to avoid the display of these messages in the present version. |
Two more methods of the window object enable you to set timeouts. These are statements (or groups of statements) that will be executed after a certain amount of time elapses. These are handy for periodically updating a Web page or for delaying a message or function.
You begin a timeout with the setTimeout() method. This method has two parameters. The first is a JavaScript statement, or group of statements, enclosed in quotes. The second parameter is the time to wait in milliseconds (thousandths of seconds). For example, this statement displays an alert dialog after 10 seconds:
ident=window.setTimeout("alert('Time's up!')",10000);
A variable (ident in this example) stores an identifier for the timeout. This enables you to set multiple timeouts, each with its own identifier. Before a timeout has elapsed, you can stop it with the clearTimeout() method, specifying the identifier of the timeout to stop:
window.clearTimeout(ident);
These timeouts execute only once; they do not repeat unless you set another timeout each time.
You can make a timeout repeat by issuing the setTimeout() method call again in the function called by the timeout. Listing 5.4 is an HTML document that demonstrates a repeating timeout.
Listing 5.4. (TIMEOUT.htm) Using the timeout methods to update a page every 2 seconds.
<HTML> <HEAD><TITLE>Timeout Example</TITLE> <SCRIPT> var counter = 0; // call Update function in 2 seconds after first load ID=window.setTimeout("Update();",2000); function Update() { counter ++; window.status="The counter is now at " + counter; document.form1.input1.value="The counter is now at " + counter; // set another timeout for the next count ID=window.setTimeout("Update();",2000); } </SCRIPT> </HEAD> <BODY> <H1>Timeout Example</H1> <HR> The text value below and the status line are being updated every two seconds. Press the RESET button to restart the count, or the STOP button to stop it. <HR> <FORM NAME="form1"> <INPUT TYPE="text" NAME="input1" SIZE="40"><BR> <INPUT TYPE="button" VALUE="RESET" onClick="counter = 0;"><BR> <INPUT TYPE="button" VALUE="STOP" onClick="window.clearTimeout(ID);"> <HR> </BODY> </HTML>
This program displays a message in the status line and in a text field every two seconds, including a counter that increments each time. You can use the RESET button to start the count over and the STOP button to stop the counting.
The setTimeout() method is used when the page first loads and again at each update. The Update() function performs the update, adding one to the counter and setting the next timeout. The RESET button sets the counter to zero, and the STOP button demonstrates the clearTimeout() method. Figure 5.7 shows Netscape's display of the timeout example after the counter has been running for a while.
Figure 5.7 : The output of the Timeout Example, as displayed by Netscape.
As you can see, timeouts can be useful for performing regular updates to a Web page's fields. You see this further with a scrolling message in Chapter 8and with a graphical clock display in < Chapter 12, " Working with Graphics in JavaScript."
The window object has three remaining methods, which enable you to manipulate the window itself:
The window object has several event handlers:
You can specify JavaScript statements or functions for these events using attributes of a Web page's <BODY> tag. For example, Listing 5.5 shows an HTML document that displays an alert message when it is loaded and another when it is unloaded.
Listing 5.5. (ONLOAD.htm) Using the onLoad and onUnload events to display dialogs.
<HTML> <HEAD><TITLE>onLoad and onUnload Example</TITLE> </HEAD> <BODY onLoad="window.alert('Hello, and welcome to this page.');" onUnload="window.alert('You unloaded the page. Goodbye!');"> <H1>The onLoad and onUnload Methods</H1> <HR> This page displays a "hello" dialog when you load it, and a "goodbye" dialog when you unload it. Annoying, isn't it? <HR> This is done through event handlers specified in this document's <BODY> tag. Aside from that tag, the rest of the document doesn't affect the dialogs. <HR> </BODY> </HTML>
This document will display a "hello" alert when it loads and a "goodbye" alert when it unloads. You can unload the page by closing the browser window or by loading a different page. Figure 5.8 shows Netscape's display of this document, including the onLoad alert.
Figure 5.8 : The output of the onLoad and onUnload example.
The location object is a property of the window object. It contains information about the current URL being displayed by the window. It has a set of properties to hold the different components of the URL, but no methods.
As you know, the URL format is used to specify the location of the Web page. Here is an example of a URL:
http://www.starlingtech.com:80/books/javascript/test.html#part2
The following are the components of the URL as they correspond with properties of the location object:
You can read the location of the current window by using the properties listed previously. In addition, you can send the user to a new URL by changing the location object's properties. For example, this command loads the Sams.net Publishing Web page:
window.location.href="http://www.mcp.com/samsnet/"
The location object has two methods:
Another child of the window object is the document object. This object represents the contents of the current HTML Web page. This object includes a wide variety of attributes that specify information about the current page.
In addition, the document object includes the form, link, and anchor objects to describe forms, links, and anchors on the page. You will look at each of these later in this chapter. The document object has no event handlers of its own.
The properties of the document
object represent characteristics of the current HTML page. Many
of these are specified in the <BODY>
tag of the document, and others are set by the browser when the
document is loaded.
Caution |
The only way to modify most of the document object's properties is to change the HTML page itself, or use JavaScript statements within the page to generate HTML dynamically. |
Several properties of the document object include information about the current document in general:
As an example, this is a short HTML document that displays its last-modified date:
<HTML><HEAD><TITLE>Test Document</TITLE></HEAD> <BODY> This page was last modified on: <SCRIPT> document.write(document.lastModified); </SCRIPT> <BR> </HTML>
This can be a useful indication to the user of when the page was
last changed, and if you use JavaScript, you don't have to remember
to update the date each time you modify the page.
Note |
The lastModified property doesn't work correctly and may cause crashes in certain platforms and Netscape versions. In addition, some Web servers don't send modification dates properly. See Chapter 14, "Debugging JavaScript Programs," for further information. |
The next set of properties of the document object concern the links, forms, anchors, and images in the HTML document:
The forms, anchors, and links objects are each discussed in their own sections later in this chapter. The images array is explained in Chapter 12.
The final set of document object properties are used to store information about color settings for the document. Again, you can't change these directly; they are specified as attributes to the document's <BODY> tag. Here are the available color properties:
In addition to these properties, the document object has a few handy methods. These can be used to control the opening and closing of documents and to output HTML as part of the document.
The simplest document object methods are also the ones you will use most often. In fact, you've used one of them already. The document.write() method prints text as part of the HTML page in a document window. This statement is used whenever you need to include output in a Web page.
An alternative statement, document.writeln(),
also prints text, but it also includes a newline (\n)
character at the end. This is handy when you want your text to
be the last thing on the line.
Tip |
Bear in mind that the newline character is ignored by HTML, except inside the <PRE> container. You will need to use the <BR> tag if you want an actual line break. |
You can only use these methods within the body of the Web page, so they will be executed when the page loads; you can't add to a page that has already loaded. You can write new content for a document, however, as the next section explains.
The document object includes open() and close() methods. Unlike the window object methods of the same name, these methods don't actually open and close new documents or windows. Instead, the open() method opens a stream; this clears the document and enables you to create a new one with the write() or writeln() methods.
The data you send to a stream isn't actually displayed until the close() method is used. You can use this to ensure that blocks of write commands execute at the same time. Chapter 9includes an example of using these methods to write new content to a frame.
You can optionally specify a MIME
document type in the document.open
command. This enables you to create a document of any type, including
images and documents used by plug-in applications. You'll learn
about plug-ins in detail in Chapter 13, "Working with Multimedia
and Plug-ins."
Note |
When you use the document.open() method, the current document is cleared. Any data already displayed in the document is erased. |
The final document method is the clear() method. It simply clears the document's contents. For example, the following statement clears the main window:
document.clear();
Warning |
The clear() method doesn't work reliably in most versions of Netscape. The best solution for clearing and updating documents is to use the open() method to clear the document window, use the write() method to write the new contents (or no contents), and then use the close() method to close the stream. |
The history object is another child (property) of the window object. This object holds information about the URLs that have been visited before and after the current one, and it includes methods to go to previous or next locations.
The history object has one property: length. This keeps track of the length of the history list-in other words, the number of different locations that the user has visited.
You might notice one thing missing from the history
object's properties: the URLs themselves. These used to be available
as a property, but Netscape removed them due to privacy concerns.
When they worked, Web pages could grab your history list and use
it for statistics, marketing, or even blackmail.
Note |
The saying "You can't change history" also applies to JavaScript. You can't modify a window's history list or delete items from the list. |
The history object's methods enable you to send the user to other locations:
As an example of the history object's methods, Listing 5.6 shows an HTML page that includes BACK and FORWARD buttons, implemented with JavaScript event handlers. These work in the same way as the browser's back- and forward-arrow buttons. The output of this example is shown in Figure 5.9.
Figure 5.9 : The BACK and FORWARD example's output in Netscape.
Listing 5.6. A Web page that uses JavaScript to include BACK and FORWARD buttons.
<HTML> <HEAD><TITLE>Back and Forward Example</TITLE> </HEAD> <BODY> <H1>Back and Forward Example</H1> <HR> This page allows you to go back or forward to pages in the history list. These should be equivalent to the back and forward arrow buttons in the browser's toolbar. <HR> <FORM NAME="form1"> <INPUT TYPE="button" VALUE="< - BACK" onClick="history.back();"> ... <INPUT TYPE="button" VALUE="FORWARD - >" onClick="history.forward();"> <HR> </BODY> </HTML>
Another child of the document object is the link object. Actually, there can be multiple link objects in a document. Each one includes information about a link to another location or anchor.
You can access link objects with the links array. Each member of the array is one of the link objects in the current page. A property of the array, document.links.length, indicates the number of links in the page.
Each link object (or member of the links array) has a list of properties defining the URL. These are the same properties as the location object, defined earlier in this chapter. You can refer to a property by indicating the link number and property name. For example, this statement assigns the variable link1 to the entire URL of the first link (index 0):
link1 = links[0].href;
Tip |
The links array also includes area objects, which are used with client-side image maps. These are explained in Chapter 12. |
The link object includes two event handlers:
You'll use the onMouseOver event to create friendly status-line descriptions for links in Chapter 8. As for the onClick event handler, it's very handy for executing a JavaScript function when the user clicks on a link. For example, this defines a link that displays an alert:
<a href="#" onClick="window.alert('This is a test.');">
Notice that I used a simple # sign as the URL in this example, to avoid sending the user to another page when the link is clicked. Another use for the onClick event handler is to prevent a link from being followed; your event handler can do this by returning false. For example, this link asks for confirmation:
<a href="sound.wav" onClick="return window.confirm('play sound?');">
If the user clicks the OK button, the link is followed because true is returned; otherwise, false is returned and the link is ignored. This might be handy for files that will take a while to download, or any situation where you want to control links with JavaScript.
anchor objects are also children of the document object. Each anchor object represents an anchor in the current document-a particular location that can be jumped to directly.
Like links, anchors can be accessed through an array: anchors. Each element of this array is an anchor object. The document.anchors.length property gives you the number of elements in the anchors array.
At least for now, the number of anchors is all you can know. The anchor objects don't include the name or locations of the anchors. The exact reason for this is a mystery, but it will hopefully be remedied in a future version of Netscape (or another browser).
Another child of the document object is the form object, which represents an HTML form. Like anchors and links, there can be several form objects within a document. You can access a form by name (specified with the NAME attribute to the <FORM> tag) or by using the forms array, which includes an element for each form.
The form has many properties that are objects themselves: the elements, or components, of the form. These are the text fields, buttons, and other objects that make up a form. You can access these by using their individual names, or once again with an array; the elements array indexes each element of the form.
Forms have been used in a few of the examples in this chapter. Because forms are one of the greatest strengths of JavaScript, there's a lot of information to cover. Chapter 6covers forms and form objects in detail.
In this chapter, you took a guided tour of the JavaScript object hierarchy, which contains objects to represent parts of the current window and document:
You should now know the JavaScript object hierarchy inside and out. Continue with one of these:
Why do I have to specify the document object, but not the window object, when using its properties and methods? | |
Good question! The reason is that the window object contains the current script, so it's treated as a default object. Also, be warned that there are situations in which you shouldn't omit the window object's name-when frames or multiple windows are involved, for example, or in an event handler. | |
When I try to close the current window with window.close(), I get an error or no result. Is there a solution? | |
This is another capability that was removed from JavaScript due to a security concern. (The last thing Netscape wants is for people to click on a button and exit Navigator immediately.) You can officially use the close() method only on windows that you opened yourself. Some versions of Netscape crash when you attempt to close the main window; the most recent version asks the user for confirmation before closing it. | |
Why is the text "JavaScript Alert:" displayed at the top of all my alert messages? Is there no way to stop this? | |
No, and it's another security feature. Without it, I could make my script display an alert with a message like "Netscape error: please enter your password" and get a few unwary users to send me their passwords. (Not that I would do that, of course.) | |
I want to make a control panel window for my Web page. Is there a way to keep this window on top at all times? | |
No, no easy way; JavaScript doesn't have an "always on top" feature. You could use the focus() method in an onBlur event handler to make it return to the top, but this doesn't always work. |