Team LiB   Previous Section   Next Section

2.2 The Window Object

The Window object represents a web browser window. In client-side JavaScript, the Window object is the global object that defines all top-level properties and methods. The properties and methods of the Window object are therefore global properties and global functions and you can refer to them by their property names without any object prefix. One of the properties of the Window object is named window and refers back to the Window object itself:

window           // The global Window object
window.document  // The document property of the window
document         // Or omit the object prefix

See the Window object in the reference section for a full list of its properties and methods. The following sections summarize the most important of these properties and methods and demonstrate key client-side programming techniques using the Window object. Note that the most important property of the Window object is document, which refers to the Document object that describes the document displayed by the browser window. The Document object is described in a section of its own following these window-related subsections.

2.2.1 Simple dialog boxes

Three methods allow you to display simple dialog boxes to the user. alert( ) lets you display a message to the user, confirm( ) lets you ask the user a yes-or-no question, and prompt( ) lets you ask the user to enter a single line of text. For example:

alert("Welcome to my home page!"); 
if (confirm("Do you want to play?")) {
    var n = prompt("Enter your name");
}

2.2.2 The status line

Most web browsers include a status line at the bottom of the window that is used to display the destination of links and other information. You can specify text to appear in the status line with the status property. The text you set on this property appears in the status area until you or the browser overwrites it with some new value. You can also set defaultStatus to specify text to appear by default when the browser is not displaying any other information in the status line. Here is an HTML hyperlink that uses JavaScript in an event handler to set the status text to something other than the URL of the link:

<a href="help.html"
   onmouseover="window.status='Help'; return true;">
Help</a>

2.2.3 Timers

Client-side JavaScript uses event handlers to specify code to be run when a specific event occurs. You can also use timers to specify code to be run when a specific number of milliseconds has elapsed. To run a string of JavaScript code after a specified amount of time, call the setTimeout( ) method, passing the string of code and the number of milliseconds. If you want to run a string of code repeatedly, use setInterval( ) to specify the code to run and the number of milliseconds between invocations. Both functions return a value that you can pass to clearTimeout( ) or clearInterval( ), respectively, to cancel the pending execution of code. For example:

var count = 0; 
// Update status line every second
var timer = setInterval("status=++count",1000);
// But stop updating after 5 seconds;
setTimeout("clearInterval(timer)", 5000);

2.2.4 System information

The navigator and screen properties of the Window object refer to the Navigator and Screen objects, which themselves define properties that contain system information, such as the name and version of the web browser, the operating system it is running on, and the resolution of the user's screen. See Navigator and Screen in the reference section for details. The Navigator object is commonly used when writing code specific to a particular web browser or web browser version:

if (navigator.appName == "Netscape" &&
    parseInt(navigator.appVersion) == 4) {
  // Code for Netscape 4 goes here.
}

2.2.5 Browser navigation

The location property of the Window object refers to the contents of the browser's location bar (the field that you type URLs into). Reading the value of this property gives you the URL that is currently being displayed. More importantly, setting the location property to a new URL tells the browser to load and display the document referred to by that URL:

// In old browsers, load a different page
if (parseInt(navigator.appVersion) <= 4)
    location = "staticpage.html";

Note that any script or event handler that sets the location property of its own window (we'll discuss multiple windows and multiple frames later in this section) is overwritten when the new document is loaded and will not continue running!

Although the location property can be queried and set as if it were a string, it actually refers to a Location object. The Location object has properties that allow you to query and set individual portions of the currently displayed URL:

// Get the substring of the URL following ?
var query = location.search.substring(1);
// Scroll to a named portion of the document
location.hash = "#top";

In addition, the reload( ) method makes the browser reload the currently displayed URL.

The history property of the Window object refers to the History object for the browser window. This object defines methods that allow you to move the browser backward and forward through its browsing history, just as the user can with the browser's Back and Forward buttons:

history.back();    // Go back once
history.forward(); // Go forward
history.go(-3);    // Go back three times

2.2.6 Window control

The Window object defines methods to move, resize, and scroll windows, and methods to give keyboard focus to and take focus away from windows. For example:

// Automatically scroll 10 pixels a second
setInterval("scrollBy(0,1)", 100);

See moveTo( ), moveBy( ), resizeTo( ), resizeBy( ), scrollTo( ) scrollBy( ), focus( ) and blur( ) in the Window object entry of the reference section for more information.

More important than these methods that manipulate an existing window are the open( ) method that creates a new browser window and the close( ) method that closes a script-created window. The open( ) method takes three arguments. The first is the URL to be displayed in the new window. The second is an optional name for the window. If a window by that name already exists, it is reused and no new window is created. The third argument is an optional string that specifies the size of the new window and the features, or chrome, that it should display. For example:

// Open a new window
w = open("new.html", "newwin", // URL and name
         "width=400,height=300," + // size
         "location,menubar," +     // chrome
         "resizable,scrollbars,status,toolbar");
// And close that new window
w.close();

Note that most browsers only allow scripts to close windows that they have opened themselves. Also, because of the recent proliferation of nuisance pop-up advertisements on the Web, some browsers do not allow scripts to open new windows at all.

2.2.7 Multiple windows and frames

As discussed previously, the open( ) method of the Window object allows you to create new browser windows that are represented by new Window objects. The window that a script is running in is the global object for that script, and you can use all the properties and methods of that Window object as if they were globally defined. When a script running in one window needs to control or interact with a different window, however, you must explicitly specify the Window object:

// Create a new window and manipulate it
var w = open("newdoc.html");  
w.alert("Hello new window");
w.setInterval("scrollBy(0,1)",50);

HTML allows a single window to have multiple frames. Many web designers choose to avoid frames, but they are still in fairly common use. JavaScript treats each frame as a separate Window object, and scripts in different frames run independently of each other. The frames property of the Window object is an array of Window objects, representing the subframes of a window:

// Scripts in framesets refer to frames like this:
frames[0].location = "frame1.html";
frames[1].location = "frame2.html";
// With deeply nested frames, you can use:
frames[1].frames[2].location = "frame2.3.html";
// Code in a frame refers to the top-level window:
top.status = "Hello from the frame";

The parent property of a Window object refers to the containing frame or window. The top property refers to the top-level browser window that is at the root of the frame hierarchy. (If the Window object represents a top-level window rather than a frame, the parent and top properties simply refer to the Window object itself.)

Each browser window and frame has a separate JavaScript execution context, and in each context, the Window object is the global object. This means that any variables declared or functions defined by scripts in the window or frame become properties of the corresponding Window object. This allows a script in one window or frame to use variables and functions defined in another window or frame. It is common, for example, to define functions in the <head> of a top-level window, and then have scripts and event handlers in nested frames call those functions using the top property:

// Code in a frame calls code in the top-level window.
top.stop_scrolling();
    Team LiB   Previous Section   Next Section