Team LiB
Previous Section Next Section

Opening and Closing Generic Windows

While the alert(), confirm(), and prompt() methods create specialized windows quickly, it is often desirable to open arbitrary windows to show a Web page or the result of some calculation. The Window object methods open() and close() are used to create and destroy a window, respectively.

When you open a window, you can set its URL, name, size, buttons, and other attributes, such as whether or not the window can be resized. The basic syntax of this method is

window.open(url, name, features, replace)

where

An example of this method is

secondwindow = open("http://www.yahoo.com", "yahoo", "height=300,width=200,
 scrollbars=yes");

This would open a window to Yahoo with height 300 pixels, width 200 pixels, and scrollbars, as shown here:

There are a variety of ways programmers create windows, but often links or buttons are used. For example:

<<a href="#" onclick="javascript: secondwindow = open('http://www.yahoo.com',
 'yahoo', 'height=300,width=200,scrollbars=yes');">>Open Window<</a>>

<<form action="#" method="get">>
<<input type="button" value="Open Window" onclick="secondwindow =
 open('http://www.yahoo.com', 'yahoo', 'height=300,width=200,scrollbars=yes');" />>
<</form>>
Note 

Be careful that you do not have a pop-up killer installed with your browser, as it may break the various window creation examples in this chapter. Remember, not all pop-ups are evil.

Once a window is open, the close() method can be used to close it. For example, the following fragment presents buttons to open and close a window. Make sure to notice the use of the secondwindow variable that contains the instance of the Window object created.

<<form action="#" method="get">>
<<input type="button" value="Open Window" onclick="secondwindow = 
open('http://www.yahoo.com', 'yahoo', 'height=300,width=200,scrollbars=yes');" />>
<<input type="button" value="Close Window" onclick="secondwindow.close();" />>
<</form>>

This usage of the close() method is rather dangerous. If the secondwindow object does not exist, you will throw an error. Reload the previous example and click the Close button immediately and you should get an error. However, if you create a window even once, you will not see an error regardless of the presence of the window on the screen, because the object probably will still be in the scope chain. In order to safely close a window, you first need to look for the object and then try to close it. Consider the following if statement, which looks to see if the secondwindow variable is instantiated before looking at it and then looks at the closed property to make sure it is not already closed.

if (secondwindow  && !secondWindow.closed)
  secondwindow.close();

Note that this previous example actually specifically relies on short circuit evaluation, because if secondwindow is not instatiated, looking at its closed property would throw an error. The following short example shows the safe use of the Window methods and properties discussed so far.

<<script type="text/javascript">>
<<!--
function openWindow()
 {
  secondWin= open('http://www.yahoo.com','example',
                  'height=300,width=200,scrollbars=yes');
 }
//-->>
<</script>>

<<form action="#" method="get">>
<<input type="button" value="Open Window" onclick="openWindow();" />>
<<input type="button" value="Close Window" onclick="if (window.secondWin) 
secondWin.close();" />>
<<input type="button" value="Check Status" onclick="if (window.secondWin)
 alert(secondWin.closed); else alert('secondWin undefined');" />>
<</form>>
Tip 

If you create a window within an (X)HTML tag’s event handler attribute, remember that the variable scope will not be known outside of that tag. If you want to control a window, make sure it is defined in the global scope.

Besides checking for existence of windows before closing, be aware that you cannot close windows that you have not created—particularly if security privileges have not been granted to the script. Furthermore, you may have a hard time closing the main browser window. If you have a statement like

window.close();

in the main browser window running the script, you might see a message like this

Click To expand

in some browsers, while others may actually close down the main window without warning, as in the case of Opera, or potentially even close down the browser, as in very old versions of Netscape.

Window Features

The list of possibilities for the feature parameter is quite rich and allows you to set the height, width, scrollbars, and a variety of other window characteristics. The possible values for this parameter are detailed in Table 12-1.

Table 12-1: Feature Parameter Values for window.open()

Feature Parameter

Value

Description

Example

alwaysLowered

yes/no

Indicates whether or not the window should always be lowered under all other windows. Does have a security risk.

alwaysLowered=no

alwaysRaised

yes/no

Indicates whether or not the window should always stay on top of other windows.

alwaysRaised=no

dependent

yes/no

Indicates whether or not the spawned window is truly dependent on the parent window. Dependent windows are closed when their parents are closed, while others stay around.

dependent=yes

directories

yes/no

Indicates whether or not the directories button on the browser window should show.

directories=yes

fullscreen

yes/no

Indicates whether or not the window should take over the full screen (IE only).

fullscreen=yes

height

Pixel value

Sets the height of the window chrome and all.

height=100

hotkeys

yes/no

Indicates whether or not the hotkeys for the browser beyond essential hotkeys such as quit should be disabled in the new window.

hotkeys=no

innerHeight

Pixel value

Sets the height of the inner part of the window where the document shows.

innerHeight=200

innerWidth

Pixel value

Sets the width of the inner part of the window where the document shows.

innerWidth=300

left

Pixel value

Specifies where to place the window relative to the screen origin. Primarily an IE-specific syntax; use screeny otherwise.

left=10

location

yes/no

Specifies if the location bar should show on the window.

location=no

menubar

yes/no

Specifies if the menu bar should be shown or not.

menubar=yes

outerHeight

Pixel value

Sets the height of the outer part of the window including the chrome.

outerHeight=300

outerWidth

Pixel value

Sets the width of the outer part of the window including the chrome.

outerWidth=300

resizable

yes/no

Value to indicate if the user should be able to resize the window.

resizable=no

screenx

Pixel value

Distance left in pixels from screen origin where window should be opened. Netscape-oriented syntax; use left otherwise.

screenx=100

screeny

Pixel value

Distance up and down from the screen origin where window should be opened. Netscape-specific syntax; use top otherwise.

screeny=300

scrollbars

yes/no

Indicates whether or not scrollbars should show.

scrollbars=no

status

yes/no

Indicates whether or not the status bar should show.

status=no

titlebar

yes/no

Indicates whether or not the title bar should show.

titlebar=yes

toolbar

yes/no

Indicates whether or not the toolbar menu should be visible.

toolbar=yes

top

Pixel value

IE-specific feature to indicate position down from the top corner of the screen to position the window; use screeny otherwise.

top=20

width

pixel value

The width of the window. You may want to use innerWidth instead.

width=300

z-lock

yes/no

Specifies if the z-index should be set so that a window cannot change its stacking order relative to other windows even if it gains focus.

z-lock=yes

Note 

Typically, in modern JavaScript implementations you can use 1 for yes and 0 for no for the features using yes/no values. However, for pure backward compatibility, the yes/no syntax is preferred.

Often when using this method, you may want to create strings to hold the options rather than to use a string literal. However, when the features are specified, they should be set one at a time with comma separators and no extra spaces. For example:

var windowOptions = "directories=no,location=no,width=300,height=300";
var myWindow = open("http://www.yahoo.com", "mywindow", windowOptions);

The next example is useful to experiment with all the various window features that can be set. It also will display the JavaScript string required to create a particular window in a text area so it can be used in a script. If the form access features seem a little cryptic, you might want to take a look at Chapter 14.

<<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">>
<<html xmlns="http://www.w3.org/1999/xhtml">>
<<head>>
<<title>>Window Creator<</title>>
<<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />>
<<script type="text/javascript">>
<<!--
function createFeatureString()
{
 var featurestring = "";
 var numelements = document.windowform.elements.length;
 for (var i= 0; i << numelements; i++)
    if ( (document.windowform.elements[i].type == "checkbox")  &&
         (document.windowform.elements[i].checked) )
 featurestring += document.windowform.elements[i].name+"=yes,";
 featurestring += "height="+document.windowform.height.value+",";
 featurestring += "width="+document.windowform.width.value+",";
 featurestring += "top="+document.windowform.top.value+",";
 featurestring += "left="+document.windowform.left.value+",";
 featurestring += "screenx="+document.windowform.screenX.value+",";
 featurestring += "screeny="+document.windowform.screenY.value;
 return featurestring;
}
function openWindow()
 {
   var features = createFeatureString();
   var url = document.windowform.windowurl.value;
   var name = document.windowform.windowname.value;
   theNewWindow = window.open(url,name,features); 
   if (theNewWindow)
    document.windowform.jscode.value = 
"window.open('"+url+"','"+name+"','"+features+"');"
   else
     document.windowform.jscode.value = "Error: JavaScript Code Invalid";
 }

function closeWindow()
{
 if (window.theNewWindow) 
  theNewWindow.close(); 
}
//-->>
<</script>>
<</head>>
<<body>>
<<form name="windowform" id="windowform" action="#" method="get">>
<<h2>>Window Basics<</h2>>
URL: <<input type="text" name="windowurl" id="windowurl" size="30" maxlength="300"
 value="http://www.yahoo.com" />><<br />>
Window Name: <<input type="text" name="windowname" id="windowname" size="30"
 maxlength="300" value="secondwindow" />><<br />>
<<h2>>Size<</h2>>
Height:    <<input type="text" name="height" id="height" size="4" maxlength="4"
value="100" />>
Width:    <<input type="text" name="width" id="width" size="4" maxlength="4"
value="100" />><<br />>
<<h2>>Position<</h2>>
Top: <<input type="text" name="top" id="top" size="4" maxlength="4" value="100" />>
Left: <<input type="text" name="left" id="left" size="4" maxlength="4" value="100"
 />> (IE)<<br />><<br />>
ScreenX: <<input type="text" name="screenX" id="screenX" size="4" maxlength="4"
 value="100" />>
ScreenY: <<input type="text" name="screenY" id="screenY" size="4" maxlength="4"
 value="100" />> (Netscape)<<br />>

<<h2>>Display Features<</h2>>
Always Lowered: <<input type="checkbox" name="alwaysLowered" id="alwaysLowered" />>
Always Raised: <<input type="checkbox" name="alwaysRaised" id="alwaysRaised" />>
Dependent: <<input type="checkbox" name="dependent" id="dependent" />>
Directories: <<input type="checkbox" name="directories" id="directories" />>
Hotkeys: <<input type="checkbox" name="hotkeys" id="hotkeys" />>
Location: <<input type="checkbox" name="location" id="location" />>
Menubar: <<input type="checkbox" name="menubar" id="menubar" />><<br />>
Resizable: <<input type="checkbox" name="resizable" id="resizable" />>
Scrollbars: <<input type="checkbox" name="scrollbars" id="scrollbars" />>
Titlebar: <<input type="checkbox" name="titlebar" id="titlebar" />>
Toolbar: <<input type="checkbox" name="toolbar" id="toolbar" />>
Z-Lock: <<input type="checkbox" name="z-lock" id="z-lock" />>
<<br />><<br />>
<<input type="button" value="Create Window" onclick="openWindow();" />>
<<input type="button" value="Close Window" onclick="closeWindow();" />>
<<br />><<br />>
<<hr />>

<<h2>>JavaScript Window.open Statement<</h2>>
<<textarea name="jscode" id="jscode" rows="4" cols="80">><</textarea>>
<</form>>
<</body>>
<</html>>

Writing to Windows

Up to now, all the examples with windows have used an existing document—either a remote URL like http://www.yahoo.com or a local file like example.htm—to load into a created window. We can actually write to windows once they are created either using the standard document.write() method or potentially even manipulate the window with DOM methods. Consider the script here,

var myWindow = open('','mywin','height=300,width=300');
myWindow.document.write('Hi there. ');
myWindow.document.write('This is my new window');
myWindow.document.close();
myWindow.focus();

which creates a simple window with a sentence of text in it as shown in Figure 12-1.

Click To expand
Figure 12-1: Simple window and its source

It is possible to write out HTML to the newly created window dynamically, so you could use something like

myWindow.document.writeln("<<html>><<head>><<title>>fun<</title>><</head>><<body>>");
myWindow.document.writeln("<<h1>>Hi from JavaScript<</h1>><</body>><</html>>");

just as easily for your document.write() statements. The next window creation example shows how the previous “Guru” example implemented with the alert() method could be modified to support more customized windows. It is no stretch to create your own form of alerts or other dialogs in a similar fashion, though setting the dialog to be truly modal would take some extra manipulation. See the section entitled “Window Extensions” later in this chapter for more information on this.

<<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">>
<<html xmlns="http://www.w3.org/1999/xhtml">>
<<head>>
<<title>>JavaScript Guru 1.1<</title>>
<<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />>
<<script type="text/javascript">>
<<!--
function customAlert(title,message)
{
  var guruWindow=window.open("","","width=300,height=200");  
  if (guruWindow != null)
    {
      var windowHTML= "<<html>><<head>><<title>>"+title+"<</title>><</head>>";
      windowHTML += "<<body bgcolor='black' text='yellow'>><<h1 align='center'>>"
      windowHTML += message + "<</h1>><<hr />><<div align='center'>>";
      windowHTML += "<<form>><<input type='button' value='CLOSE'
 onclick='self.close()'>>";
      windowHTML += "<</form>><</div>><</body>><</html>>";
      guruWindow.document.write(windowHTML);
      guruWindow.focus();
      return;
     }
}

function askGuru()
{
  var question = prompt("What is your question o' seeker of knowledge?","")
  if (question != null)
    {
     if (question == "")
      customAlert("Angry Guru", "You insult me!");
     else
      customAlert("Bored Guru", "Don't waste my time.");
    } 
}
//-->>
<</script>>
<</head>>
<<body>>
<<div align="center">>
<<h1>>JavaScript Guru 1.1<</h1>>
<<hr />>
<<form action="#" method="get">>
<<input type="button" value="Ask the Guru" onclick="askGuru();" />>
<</form>>
<</div>>
<</body>>
<</html>>

The last example would only be useful to write content to a document as it loaded. However, we can easily use proprietary Document objects like document.all or the more standard DOM methods to modify windows after load time, as briefly demonstrated in the next section.

DOM Methods and Windows

Using DOM statements, we could of course insert and change the HTML in the new document at will. The main difference is that you must make sure to use the new window’s name when accessing a DOM method or property. For example, if you had a window called newWindow, you would use statements like

var currentElement = newWindow.document.getElementById("myheading");

to retrieve a particular element in the other window. The following simple example shows how information entered in one window can be used to create an element in another window.

<<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">>
<<html xmlns="http://www.w3.org/1999/xhtml">>
<<head>>
<<title>>DOM Window Add<</title>>
<<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />>
<<script type="text/javascript">>
<<!--
function domWindowAdd()
{
  var currentElement;
  if ((window.myWindow)  && (myWindow.closed == false))
   {
     var str = document.testForm.textToAdd.value;
     var theString = myWindow.document.createTextNode(str);
     var theBreak = myWindow.document.createElement("br");

     currentElement = myWindow.document.getElementById('heading1');
     currentElement.appendChild(theString);
     currentElement.appendChild(theBreak); 

     myWindow.focus(); 
   }
}
// Make the window to add to 
var myWindow = open('','mywin','height=300,width=300');
myWindow.document.writeln("<<html>><<head>><<title>>fun<</title>><</head>><<body>>");
myWindow.document.writeln("<<h1 id='heading1'>>Hi from JavaScript<</h1>>
<</body>><</html>>");
myWindow.document.close();
myWindow.focus();
//-->>
<</script>>
<</head>>
<<body>>
<<h1>>DOM Window Interaction<</h1>>
<<form name="testForm" id="testForm" action="#" method="get">>
  <<input type="text" name="textToAdd" id="textToAdd" size="30" />>
  <<input type="button" value="Add Text" onclick="domWindowAdd();" />>
<</form>>
<</body>>
<</html>>

This example is simply to remind you of the use of these techniques. See Chapter 10 for a more complete discussion of document manipulation with DOM methods. Before moving on to the methods and events associated with windows, we need to cover one last detail on how windows interact with each other.


Team LiB
Previous Section Next Section