Script School Classroom

School Map:  Home / Enroll $ Student Records; Class  
$ News @ LIVE Tech Radio * Support/FAQ | Store | FORUMS

Script School Course #7 - JavaScript -  Week #3

Printable Version of this page HERE

Opening and Closing Browser Windows

JavaScript gives You the ability to create new browser windows with Your scripts. You can control which window elements appear - the status bar, tool bar, menu bar, location bar, scroll bar, and if it is resizable... You can also make a custom sized window, position it on the screen, and place it above or below the current window.  The contents can be pre written HTML documents or they can be written 'on the fly'. You can also rewrite the 'parent' window document from another window - for example, a 'Table of Contents' pop-up.  ( However, with the popularity of 'pop-up blockers', if this is the only way to navigate Your site, it might be a good idea to let Your users know that they'll have to allow pop-ups and JavaScript if they want to see Your site! )

Opening a new Window

To open a new window, use the  open()  method of the window object.  While the full phrase  window.open()  is optional outside Event Handlers, it's a good general practice. Otherwise, the JavaScript interpreter will see it as a call to the  open()  method of the document object, which we'll be discussing shortly. 


   var reference = window.open("url", "name", "elements");
   

 window.open()  takes three arguments in quotes, separated by commas:


   var mywindow = window.open("http://www.mysite.com/new_window.htm","NewWindow",
   "width=400,height=350,scrollbars=yes,toolbar=no,status=yes,resizable=yes,menubar=no,location=no");
   

The line of code above can be placed in a function within <SCRIPT> tabs in the <HEAD> to open a new window:


   function openMyWindow()
   {
      var mywindow = window.open("new_window.htm","NewWindow",
      "width=400,height=350,scrollbars=yes,toolbar=no,status=yes,resizable=yes,menubar=no,location=no");
   }
   

Which You could call from an onClick event handler:


   <FORM>
     <INPUT TYPE="button" VALUE="Open Window" onClick="openMyWindow()"  
	           style="color:#0000FF; background-color:#EEEEFF">
   </FORM>

Which gives us: ( live example - try it )

Positioning Windows

To place a window where You want it on the screen, set the aspects  left  and  top  in pixels, in the elements list argument in the  open()  method.  When both are set to zero it positions the window at the top left of the screen.   screen.height  and  screen.width  return their respective values in pixels from the top left.  If You want to get the 'live' area inside the window use  screen.availHeight  and  screen.availWidth   The settings for width and top are inserted as variables by joining the Strings with the  +  operator... see Week 1 of this class.


   // set Global variable: positionedwindow to null   
   var positionedwindow = null;   
   function footnote()
{
var toploc = screen.height - 130;
var winwidth = screen.width - 10;
var positionedwindow = window.open("footnote.html", "foot",
"width="+ winwidth +",height=100,scrollbars=yes,top="+ toploc +",left=0"); positionedwindow.focus();
}

Closing Windows

To close a window, use the close() method of the window object.
If You want to close a window from itself, the statements:  window.close()   or it's equivalent:  self.close()  will do it. The Footnotes window uses:


   <a href="javascript:self.close()"
   onMouseOver="window.status='Close Window'; return true;" 
   onMouseOut="window.status=''; return true;">Close Window</a>
   

Or, for a button:


     <FORM>
        <INPUT TYPE="button" VALUE="Close Window" onClick="window.close()"  
	           style="color:#FF0000; background-color:#FFEEEE">
     </FORM>

Closing a Window from another Window - using the reference

Well, we don't want to close this window, so let's try closing the footnote example - from this window.  By using the reference variable created when the window was opened, You can close another window from the current one.   Since the reference in the last example, Footnotes, was: positionedwindow it is used in the onClick Event Handler:

  
     <FORM>
        <INPUT TYPE="button" VALUE="Close Window" onClick="positionedwindow.close()"  
	           style="color:#FF0000; background-color:#FFEEEE">
     </FORM>
	 

Creating:  (live example - click the Footnotes button to open the window again first)

   

Actually, for this function to work properly, we declare the reference variable as a Global variable.  var positionedwindow = null;  That is, outside the function first.  The scope - or availability - of a variable declared within a function is limited to that function. Scope is discussed in Week #1 of this course.  We could  return  the reference from the function as we create a Global Scope variable - if the function is called in the main script - not an Event Handler. Otherwise, if a Global isn't created, the reference is lost when the run of the function is done.  Of course we could also reestablish a reference from the name as You will see in the Navigator example in just a moment.

We also use the  window.focus()  method to put the new window on top of all other windows. Otherwise clicking the Open Window button more than once in this window would focus this window, hiding the new window. Of course, any stray click in a window will focus it, bringing it to the top of all other windows.

So the script containing our function to open the window changes to:

  
     var mywindow = "";
     function openMyWindow()
     {
      mywindow = window.open("new_window.htm","NewWindow",
      "width=400,height=350,scrollbars=yes,toolbar=no,status=yes,resizable=yes,menubar=no,location=no");
	  mywindow.focus();
     }
  
  

Closing Windows created by scripts in other pages

To close a window created by a script in another page, get a new reference using the window's name with an empty string "", for the url argument in a  window.open()  statement. A new window will not be opened - but, the reference can be used to get properties and call methods of: name.  You will see this used in the Navigator Example.


   var newreference = window.open("","WindowName");
   newreference.close();

Parent / Child Relationships

A window that creates another is called the 'parent' of the new window. The new window is known as the 'child'. We have already seen how a window can refer to it's own children or the children of other windows by using the reference or perhaps after getting a new reference using a name. Any open window can be referred to this way.  JavaScript also has the property keyword:  opener  to refer to a child window's parent. For example, if You have a button that causes the parent to show a picture, You may want to assure that the parent window exists.  The presence of the parent can be checked with it's property keyword:  closed   The code below will reopen the parent window if it has been closed:


   if (window.opener.closed)
   {
      var newparent = window.open("parentURL.htm", "parentwindow");
   }

When You are fully done with a window, set the opener property to keyword:  null  so JavaScript can free up memory:  window.opener = null You might want to do this if a site opens many new windows as children. For example, a sequence of pages in a long book. Of course, unless You must control the new window's properties, new windows can be opened with regular HTML without memory considerations.

Altering the Contents of one Window from another

We first saw the write() method of the document object in Week 1.  The following example uses the similar writeln() method of the document object. The only difference is that writeln() causes the next write() or writeln() to start on the next line. We are writing to the document, as though we were writing an HTML page in an editor.  The document object is then interpreted by the browser window.  The script rewrites to the same window it created each time a new Item is clicked, changing the TITLE bar, the text in the window, and the color of the background of the window.  It rewrites to the same window, instead of recreating a new one, since the window already exists.  We could have just as easily changed pictures or CSS settings.  Included are links to open and close the parent Navigator window from it's child.  Take a look at the example and the script for the first child we open from this page, which is annotated with comments:

   

Pop-Unders

Within the script example for the Navigator we open a window under all the other open windows using the window method:  window.blur()  When You try the example, click Area 3 Item 2, then minimize all the other windows You have open - and viola - there it is!  From the script:

   
    if (updn == "dn")
{
subwindow.blur(); } else {
subwindow.focus();
}

Assignments for this Week

Basic Assignment

Write a script that:

  1. Opens a pop-up window of a particular size and position on the screen from a button or image link.
    -and -
  2. Opens a pop-under window with the onLoad or onUnload Event Handler.  Include an image or banner ad.

Advanced Assignment

Write a script that:
  1. Opens a window which is then written to 'on-the-fly' with various images from links on the main page. 
        ( This is faster than opening a new window for each image -
          especially if the images are preloaded by the main window before the links are clicked. )
    - and -
  2. Opens a pop-up window after an interval of 30 seconds - if - no link on a special list has been clicked.
    - and -
  3. Opens a 'special free image' pop-under window - if - they click a link before a timeout of 15 seconds.
    Show a countdown.

Hints:
For 2 & 3: Write to a variable through onClick Event Handler.
For 3: See Week 2 of this class for a live clock example.
Subtract a second each loop instead of adding one.
Set the date object with a variable.

Need help with your assignment or have questions about this week's course?

About The Instructors

TDavid is co-owner, programmer and webmaster for several sites devoted to programming including his own http://www.tdscripts.com/ He has done custom programming in various programming languages for companies all over the world. Every Friday at 2pm PST you can catch his weekly radio show dedicated to the technical side of webmastering and programming at http://www.scriptschool.com/radio/

LogSpirit is a student of Script School, the co-author of this course and available for hire for custom programming.

Printable Version of this page HERE

School Map:  Home / Enroll $ Student Records; Class  
$ News @ LIVE Tech Radio * Support/FAQ | Store

Advertising | Link To Us | Privacy 
Copyright 2000-2002 Script School Productions / KMR Enterprises 
No part of this website may be reproduced, copied and/or distributed in any medium 
without express written permission