10. Using Windows and Frames wax ka badal

Controlling Windows with Objects wax ka badal

In [Hour 4], "Working with the Document Object Model (DOM)," you learned that you can use DOM objects to represent various parts of the browser window and the current HTML document. You also learned that the history, document, and location objects are all children of the window object.

In this hour, you'll take a closer look at the window object itself. As you've probably guessed by now, this means you'll be dealing with browser windows. A variation of the window object also enables you to work with frames, as you'll see later in this hour.

The window object always refers to the current window (the one containing the script). The self keyword is also a synonym for the current window. As you'll learn in the next sections, you can have more than one window on the screen at the same time, and can refer to them with different names.

Properties of the window Object wax ka badal

Although there is normally a single window object, there might be more than one if you are using pop-up windows or frames. As you learned in [Hour 4], the document, history, and location objects are properties (or children) of the window object. In addition to these, each window object has the following properties:

  • window.closed Indicates whether the window has been closed. This only makes sense when working with multiple windows because the current window contains the script and cannot be closed without ending the script.
  • window.defaultstatus and window.status The default message for the status line, and a temporary message to display on the status line. Some recent browsers disable status line changes by default, so you might not be able to use these.
  • window.frames[] An array of objects for frames, if the window contains them.
  • window.name The name specified for a frame, or for a window opened by a script.
  • window.opener In a window opened by a script, this is a reference to the window containing the script that opened it.
  • window.parent For a frame, a reference to the parent window containing the frame.
  • window.screen A child object that stores information about the screen the window is in—its resolution, color depth, and so on.
  • window.self A synonym for the current window object.
  • window.top A reference to the top-level window when frames are in use.
By the Way
The properties of the window.screen object include height, width, availHeight, and availWidth (the available height and width rather than total), and colorDepth, which indicates the color support of the monitor: 8 for 8-bit color, 32 for 32-bit color, and so on.

Creating a New Window wax ka badal

One of the most convenient uses for the window object is to create a new window. You can do this to display a document—for example, a pop-up advertisement or the instructions for a game—without clearing the current window. You can also create windows for specific purposes, such as navigation windows.

You can create a new browser window with the window.open() method. A typical statement to open a new window looks like this:

WinObj=window.open("URL", "WindowName", "Feature List");

The following are the components of the window.open() statement:

  • The WinObj variable is used to store the new window object. You can access methods and properties of the new object by using this name.
  • The first parameter of the window.open() method is a URL, which will be loaded into the new window. If it's left blank, no web page will be loaded. In this case, you could use JavaScript to fill the window with content.
  • The second parameter specifies a window name (here, WindowName). This is assigned to the window object's name property and is used to refer to the window.
  • The third parameter is a list of optional features, separated by commas. You can customize the new window by choosing whether to include the toolbar, status line, and other features. This enables you to create a variety of "floating" windows, which might look nothing like a typical browser window.

The features available in the third parameter of the window.open() method include width and height, to set the size of the window in pixels, 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");

Opening and Closing Windows wax ka badal

Of course, you can close windows as well. The window.close() method closes a window. Browsers don't normally allow you to close the main browser window without the user's permission; this method's main purpose is for closing windows you have created. For example, this statement closes a window called updatewindow:

updatewindow.close();

As another example, [Listing 10.1] shows an HTML document that enables you to open a small new window by pressing a button. You can then press another button to close the new window. The third button attempts to close the current window. Depending on your browser and its settings, this might or might not work. If it does close the window, most browsers will ask for confirmation first.

Listing 10.1. 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>
<p>Use the buttons below to test opening and closing windows in JavaScript.</p>
<hr>
<form NAME="inform">
<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>
<p><input TYPE="button" VALUE="Close Main Window"
onClick="window.close();"></p>
</form>
<br><p>Have fun!</p>
<hr>
</body>
</html>

This example uses simple event handlers to do its work, one for each of the buttons. [Figure 10.1] shows Firefox's display of this page, with the small new window on top.

Moving and Resizing Windows wax ka badal

The DOM also enables you to move or resize windows. Although earlier browsers placed some restrictions on this, most modern browsers allow you to move and resize any window freely. You can do this using the following methods for any window object:

  • window.moveTo() moves the window to a new position. The parameters specify the x (column) and y (row) position.
  • window.moveBy() moves the window relative to its current position. The x and y parameters can be positive or negative, and are added to the current values to reach the new position.
  • window.resizeTo() resizes the window to the width and height specified as parameters.
  • window.resizeBy() resizes the window relative to its current size. The parameters are used to modify the current width and height.

As an example, [Listing 10.2] shows an HTML document with a simple script that enables you to resize or move the main window.

Listing 10.2. Moving and Resizing the Current Window
<html>
<head>
<title>Moving and resizing windows</title>
<script language="javascript" type="text/javascript">
function DoIt() {
if (document.form1.w.value && document.form1.h.value)
self.resizeTo(document.form1.w.value, document.form1.h.value);
if (document.form1.x.value && document.form1.y.value)
self.moveTo(document.form1.x.value, document.form1.y.value);
}
</script>
</head>
<body>
<h1>Moving and Resizing Windows</h1>
<form name="form1">
<b>Width:</b> <input type="text" name="w"><br>
<b>Height:</b> <input type="text" name="h"><br>
<b>X-position:</b> <input type="text" name="x"><br>
<b>Y-position:</b> <input type="text" name="y"><br>
<input type="button" value="Change Window" onClick="DoIt();">
</form>
</body>
</html>

In this example, the DoIt() function is called as an event handler when you click the Change Window button. This function checks whether you have specified width and height values. If you have, it uses the self.resizeTo() method to resize the current window. Similarly, if you have specified x and y values, it uses self.moveTo() to move the window.

Depending on their settings, some browsers might not allow your script to resize or move the main window. In particular, Firefox can be configured to disallow it. You can enable it by selecting Tools, Options from the menu. Select the Content tab, click the Advanced button next to the Enable JavaScript option, and enable the Move or Resize Existing Windows option.

Watch Out!
This is one of those JavaScript features you should think twice about before using. These methods are best used for resizing or moving pop-up windows your script has generated—not as a way to force the user to use your preferred window size, which most users will find very annoying. You should also be aware that browser settings may be configured to prevent resizing or moving windows, so make sure your script still works even without resizing.

Using Timeouts wax ka badal

Sometimes the hardest thing to get a script to do is to do nothing at all—for a specific amount of time. Fortunately, JavaScript includes a built-in function to do this. The window.setTimeout method enables you to specify a time delay and a command that will execute after the delay passes.

By the Way
Timeouts don't actually make the browser stop what it's doing. Although the statement you specify in the setTimeout method won't be executed until the delay passes, the browser will continue to do other things while it waits (for example, acting on event handlers).

You begin a timeout with a call to the setTimeout() method, which 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, the following statement displays an alert dialog box after 10 seconds:

ident=window.setTimeout("alert('Time's up!')",10000);
Watch Out!
Like event handlers, timeouts use a JavaScript statement within quotation marks. Make sure that you use a single quote (apostrophe) on each side of each string within the statement, as shown in the preceding example.

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);

Updating a Page with Timeouts wax ka badal

Normally, a timeout only happens once because the statement you specify in the setTimeout() method statement is only executed once. But often, you'll want your statement to execute over and over. For example, your script might be updating a clock or a countdown and need to execute once per second.

You can make a timeout repeat by issuing the setTimeout() method call again in the function called by the timeout. [Listing 10.3] shows an HTML document that demonstrates a repeating timeout.

Listing 10.3. Using Timeouts to Update a Page Every Two Seconds
<html>
<head><title>Timeout Example</title>
<script language="javascript" type="text/javascript"gt;
var counter = 0;
// call Update function in 2 seconds after first load
ID=window.setTimeout("Update();",2000);
function Update() {
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><p>
The text value below is being updated every two seconds.
Press the RESET button to restart the count, or the STOP button to stop it.
</p><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);">
</form>
<hr>
</body>
</html>

This program displays a message 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.

This script calls the setTimeout() method when the page 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 10.2] shows Internet Explorer's display of the timeout example after the counter has been running for a while.

By the Way
This example and the next one use buttons, which are a simple example of what you can do with HTML forms and JavaScript. You'll learn much more about forms in [Hour 11], "Getting Data with Forms."

Displaying Dialog Boxes wax ka badal

The window object includes three methods that are useful for displaying messages and interacting with the user. You've already used these in some of your scripts. Here's a summary:

  • window.alert(message) displays an alert dialog box, shown in [Figure 10.3]. This dialog box simply gives the user a message.
  • window.confirm(message) displays a confirmation dialog box. This displays a message and includes OK and Cancel buttons. This method returns true if OK is pressed and false if Cancel is pressed. A confirmation is displayed in [Figure 10.4].
  • window.prompt(message,default) displays a message and prompts the user for input. It returns the text entered by the user. If the user does not enter anything, the default value is used.

To use the confirm() and prompt() methods, use a variable to receive the user's response. For example, this statement displays a prompt and stores the text the user enters in the text variable:

text = window.prompt("Enter some text","Default value");
Did you Know?
You can usually omit the window object when referring to these methods because it is the default context of a script (for example, alert("text")).

Creating a Script to Display Dialog Boxes wax ka badal

As a further illustration of these types of dialog boxes, [Listing 10.4] shows an HTML document that uses buttons and event handlers to enable you to test dialog boxes.

Listing 10.4. 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">
<p><input TYPE="button" VALUE="Display an Alert"
onClick="window.alert('This is a test alert.'); "></p>
<p><input TYPE="button" VALUE="Display a Confirmation"
onClick="window.confirm('Would you like to confirm?');"></p>
<p><input TYPE="button" VALUE="Display a Prompt"
onClick="window.prompt('Enter some Text:','This is the default value');">
</p>
</form>
<br>Have fun!
<hr>
</body>
</html>

This document displays three buttons, and each one uses an event handler to display one of the dialog boxes.

[Figure 10.5] shows the script in [Listing 10.4] in action. The prompt dialog box is currently displayed and shows the default value.

Working with Frames wax ka badal

Browsers also support frames, which enable you to divide the browser window into multiple panes. Each frame can contain a separate URL or the output of a script.

Using JavaScript Objects for Frames wax ka badal

When a window contains multiple frames, each frame is represented in JavaScript by a frame object. This object is equivalent to a window object, but it is used for dealing specifically with that frame. The frame object's name is the same as the NAME attribute you give it in the <frame> tag.

Remember the window and self keywords, which refer to the current window? When you are using frames, these keywords refer to the current frame instead. Another keyword, parent, enables you to refer to the main window.

Each frame object in a window is a child of the parent window object. Suppose you define a set of frames using the following HTML:

<frameset ROWS="*,*" COLS="*,*">
<frame NAME="topleft" SRC="topleft.htm">
<frame NAME="topright" SRC="topright.htm">
<frame NAME="bottomleft" SRC="botleft.htm">
<frame NAME="bottomright" SRC="botright.htm">
</frameset>

This simply divides the window into quarters. If you have a JavaScript program in the topleft.htm file, it would refer to the other windows as parent.topright, parent.bottomleft, and so on. The keywords window and self would refer to the topleft frame.

By the Way
If you use nested framesets, things are a bit more complicated. window still represents the current frame, parent represents the frameset containing the current frame, and top represents the main frameset that contains all the others.

The frames Array wax ka badal

Rather than referring to frames in a document by name, you can use the frames array. This array stores information about each of the frames in the document. The frames are indexed starting with zero and beginning with the first <frame> tag in the frameset document.

For example, you could refer to the frames defined in the previous example using array references:

  • parent.frames[0] is equivalent to the topleft frame.
  • parent.frames[1] is equivalent to the topright frame.
  • parent.frames[2] is equivalent to the bottomleft frame.
  • parent.frames[3] is equivalent to the bottomright frame.

You can refer to a frame using either method interchangeably, and depending on your application, you should use the most convenient method. For example, a document with 10 frames would probably be easier to use by number, but a simple two-frame document is easier to use if the frames have meaningful names.

Try it Yourself — Using Frames with JavaScript wax ka badal

As a simple example of addressing frames using JavaScript, you will now create an HTML document that divides the window into four frames, and a document with a script for the top-left corner frame. Buttons in the top-left frame will trigger JavaScript event handlers that display text in the other frames.

To begin, you will need a frameset document. [Listing 10.5] shows a simple HTML document to divide the window into four frames.

Listing 10.5. An HTML Document That Divides the Window into Four Frames
<frameset ROWS="*,*" COLS="*,*">
<frame NAME="top_left" SRC="topleft.html">
<frame NAME="top_right" SRC="">
<frame NAME="bottom_left" SRC="">
<frame NAME="bottom_right" SRC="">
</frameset>

The first frame defined here, top_left, to will contain an HTML document and a simple script. [Listing 10.6] shows the HTML and JavaScript code for the top-left frame.

Listing 10.6. The HTML and JavaScript for the Frame Example
<html>
<head>
<title>Frame Test</title>
<script language="javascript" type="text/javascript">
function FillFrame(framename) {
// Find the object for the frame
theframe=parent[framename];
// Open and clear the frame's document
theframe.document.open();
// Create some output
theframe.document.write("<h1>JavaScript Output</h1>");
theframe.document.write("<p>This text is in the ");
theframe.document.write(framename + " frame.</p>");
}
</script>
</head>
<body>
<h1>Frame Test</h1>
<form name="form1";>
<input type="button" value="Top right"
onClick="FillFrame('top_right');">
<input type="button" value="Bottom left"
onClick="FillFrame('bottom_left');">
<input type="button" id="js" value="Bottom right"
onClick="FillFrame('bottom_right');">
</form>
</body>
</html>

This document defines three buttons with event handlers that call the FillFrame() function with a parameter for the frame name. The function finds the correct child of the parent window object for the specified frame, uses document.open to create a new document in the frame, and uses document.write to display text in the frame.

To try this example, save [Listing 10.6] as topleft.html in the same folder as the frameset document from [Listing 10.5], and load [Listing 10.5] into a browser. [Figure 10.6] shows the result of this example after all three buttons have been clicked.

Summary wax ka badal

In this hour, you've learned how to use the window object to work with browser windows, and used its properties and methods to set timeouts and display dialog boxes. You've also learned how JavaScript can work with framed documents.

In the next hour, you'll move on to another unexplored area of the JavaScript object hierarchy—the form object. You'll learn how to use forms to create some of the most useful applications of JavaScript.

Q&A wax ka badal

Q1
When a script is running in a window created by another script, how can it refer back to the original window?
A1
JavaScript 1.1 and later include the window.opener property, which lets you refer to the window that opened the current window.
Q2
I've heard about layers, which are similar to frames, but more versatile, and are supported in the latest browsers. Can I use them with JavaScript?
A2
Yes. You'll learn how to use layers with JavaScript in [Hour 13], "Using the W3C DOM."
Q3
How can I update two frames at once when the user clicks on a single link?
A3
You can do this by using an event handler, as in [Listing 10.6], and including two statements to load URLs into different frames.

Quiz Questions wax ka badal

Test your knowledge of the DOM's window features by answering the following questions.

1. Which of the following methods displays a dialog box with OK and Cancel buttons, and waits for a response?

  1. window.alert
  2. window.confirm
  3. window.prompt

2. What does the window.setTimeout method do?

  1. Executes a JavaScript statement after a delay
  2. Locks up the browser for the specified amount of time
  3. Sets the amount of time before the browser exits automatically

3. You're working with a document that contains three frames with the names first, second, and third. If a script in the second frame needs to refer to the first frame, what is the correct syntax?

  1. window.first
  2. parent.first
  3. frames.first

Quiz Answers wax ka badal

1. b. The window.confirm method displays a dialog box with OK and Cancel buttons.

2. a. The window.setTimeout method executes a JavaScript statement after a delay.

3. b. The script in the second frame would use parent.first to refer to the first frame.

Exercises wax ka badal

If you want to study the window object and its properties and methods further, perform these exercises:

  • Return to the date/time script you created in [Hour 2], "Creating Simple Scripts." This script only displays the date and time once when the page is loaded. Using timeouts, you can modify the script to reload automatically every second or two and display a "live" clock. (Use the location.reload() method, described in [Hour 4].)
  • Modify the examples in Listings 10.5 and 10.6 to use three horizontal frames instead of four frames in a grid. Change the buttons to make it clear which frame they will affect.