CIS 89C  Client-Side Programming with JavaScript

 

Unit 19 – Windows (week 5)

 

References:

 

McDuffie - Chapter 11 Windows and Frames

Quigley – Section 10.1.2 Working with the window Object

 

Topics:

 

Opening statement - McDuffie page 327

Targeting - McDuffie page 328

Opening and closing windows - McDuffie page 344, including material from

            Quigley page 214

Pop up window - McDuffie page 348

Writing to windows dynamically - McDuffie page 356

Don't get framed - McDuffie page 365

Summary - McDuffie page 368

 

References:

 

JavaScript by Example, by Ellie Quigley,

2003, Prentice Hall ISBN 0-13-140162-9

 

JavaScript , The Definitive Guide, Fifth Edition by David Flanagan,

2006, O'Reilly ISBN-13:  978-0-596-10199-2

 

 

 

***********************************************************

Opening statement

 

New windows can be opened with just XHTML,

JavaScript is needed to control the size, location, and other window attributes.

Of course, JavaScript is also required when you wish to write dynamically to a window.

 

Similar techniques can also be used with framesets.

framesets are not used as much any more, so we will skip most of framesets.

 

***********************************************************

Targeting in HTML

 

The target attribute in the <a> tag is deprecated, but new techniques have not yet been developed, so it is still commonly used in HTML and XHTML.

The target specifies the window where a new page is to be opened.

 

The <a> tag has a target attribute.

The default target is _self:

 

<a href="next_page.html" target="_self">

 

You can leave this default target off, and get the same result.

_self means the new page is loaded in the same window, which previously contained the old page.

 

You can specify a new window by giving it a name.

This is the technique we will usually be using with JavaScript:

 

<a href="first_detail.html" target="details">

 

Then the new page loads into a new window.

The new window has the name "details".

.

If you use the same target name again, the new page will load into the previously specified named window.

 

<a href="second_detail.html" target="details">

 

It is also possible to specify that all new pages be loaded into a specified window, by using the base tag within the head container:

 

<head>

  <base target="detail" />

</head>

<body>

  <a href="first_detail">First Detail</a>

  <a href="second_detail">Second Detail</a>

</body>

 

These pages will load into the "detail" window, rather than the current window.

 

When a new window is created, it is given focus, and appears on top of all other windows.

Loading into an existing window does not automatically give it focus, so it may be hidden behind other windows.

 

Another special name can be used to load a new page into a new window.

 

target="_blank"

 

This works like a new named window, except the new window is not given a name.  Without a name, you cannot reference that window again.

 

There are also two special names for targets that were used in framesets.

Framesets are not used much anymore.

We will omit discussion of framesets from this course.

_top                is the top level frameset, that contains the other frames and

framesets in this set.

_parent           is the frameset containing the current frame.

 

There is no target to specify opening in a new tab. 

(

Perhaps there will be something to do this in CSS 3.

It is not in CSS2.

There are some discussions of putting this, and a better replacement for

the <a target="---"> in CSS3.

)

 

***********************************************************

Opening and closing windows

 

Windows in the Document Object Model

 

Using JavaScript you can open and close windows.  You can specify their size, location, and other properties.

 

In the Document Object Model, there is a hierarchy of contained objects, just as there is in XHTML.  For example the title is contained within the XHTML head element:

 

<head>

  <title>Sample</title>

</head>

 

In the Document Object Modes, there is the corresponding hierarchy.

The title object is contained in the head object.

 

The object at the top of the hierarchy is the window object.

The document object is contained in the window object.

This corresponds to a window in the client machine, which contains an XHTML document.

 

When we use the document object, we could specify it as:

 

window.document

 

Actually, we do not specify the window object when we use the document object.

In client web page processing, window is the default global object.

The window is the parent of the document object.

The window is the default global object, so we do not need to explicitly write window.  Because window is the default, we can just write:

 

document

 

And the fact that the document is always in the current window is always understood.

 

Window properties

 

There are several window properties, including:

 

document       A reference to the document object that is currently displayed in

the window.

history             A reference to the history object, that contains recently

loaded URLs

location           The URL of the current contents of the window

name              The name of the window (which we were just talking about)

opener            A reference to the window that opened this window

screen            A reference to the screen object that contains the window

and many other properties.

 

There are also several methods for window objects, including:

 

alert(text)                                Creates an alert box

blur()                                       Removes focus from the window

clearInterval(timer)                Clear an interval timer

clearTimeout(timer)              Clears a timer            ( NOTE: lower case o )

close()                                    Closes the window

confirm()                                 Dialog box that allows the user to say yes or no

focus()                                    Gives focus to the window

open(url, name, options)      Opens a new window

prompt(text, defaultInput)      Creates a prompt box, asking the user to type

scroll(x, y)                               Scroll to the specified pixel position in the window

setInterval(expression, ms, arguments)      Set timer interval

setTimeout(expression, ms, arguments) Set timeout       (NOTE: lower case o ??)

and many other methods.

 

We have used some of these. 

They are "global".  That is we specified them without specifying a parent object.

Like the document object, these methods have the window object understood as the parent, by default.  "global" in the DOM means a child of the window.

 

Complete lists of Document Object Model classes, properties, and methods are given in:

JavaScript, The Definitive Guide by David Flanagan

 

Opening a pop-up window (Opening and Closing Windows in Quigley)

 

Format from page 217 in "JavaScript by Example" by Ellie Quigley:

var window_object = window.open("url", windowname, options);

where:

url is replaced by the url of the new page to be opened in the window

windowName is replaced by a name, which is given to the new window

options are optional options for the open process.

The options for the window.open method are the features described in:

Client-Side JavaScript Reference section, in the description of the Window.open() features in "JavaScript , The Definitive Guide" by David Flanagan.

 

The following code is from my unit 19-windows; sample-2-open.

It follows Example 10.7 in "JavaScript by Example" by Ellie Quigley.

 

JUST COPY THE BOLD FACE CODE TO THE BLACKBOARD

 

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<!--

  by Ira Oldham

-->

<html xmlns="http://www.w3.org/1999/xhtml">

  <head>

    <title>

      Window open and close

    </title>

    <link rel="stylesheet" type="text/css" href="sample.css" title="Course Style" />

    <script type="text/javascript" src="sample-2-open.js" />

  </head>

  <body>

    <div class="outer-div">

      <h2>Cleo reaching</h2>

      <p>

        The image will open in a new window or tab.<br />

        <a href="javascript:newWindow();">Cleo reaching</a><br />

        <button onclick="closeWindow();">close the Cleo window</button>

      </p>

    </div>

 

 

      <div id="functions">

 

      <span id="pre_intro">A copy of the JavaScript functions in the head element:</span>

 

      <pre>

 

// sample-2-open.js

// This sample shows opening and closing a window

 

// global variable for the new window object

var winObj;

 

// open a new window with kit2.gif

function newWindow()

  {

  winObj = open("../imageskit2.gif", "cleo");

  }

 

// close the new window

function closeWindow()

  {

  winObj.close();

  }

 

      </pre>

 

    </div>

 

  </body>

</html>

 

Comments:

- The newWindow JavaScript function is called by href in the <a> element by using the javascript: pseudoProtocol.

NOTE: When the attribute is NOT an event handler, you must use javascript: before the JavaScript code.

When the attribute is an event handler, it expects JavaScript; just write the JavaScript code.

- The url and a name for the new window are specified in the open method of the current window object (The current window object is the current object by default).

- The new window opens, displaying the kit2.gif image.

- Notice that I made the winObj a global variable, so it can be referenced from the newWindow() and closeWindow() functions

 

You can use the close method to close a window.

In this example, there is an onclick handler that calls the function that closes the window.

 

 

***********************************************************

Pop up window

 

Lets look at the options for the open() method.

 

Format from page 217 in "JavaScript by Example" by Ellie Quigley:

var window_object = window.open("url", windowname, options);

where:

url is replaced by the url of the new page to be opened in the window

windowName is replaced by a name, which is given to the new window

options are optional options for the open process.

The options for the window.open method are the features described in:

Client-Side JavaScript Reference section, in the description of the Window.open() features in "JavaScript , The Definitive Guide" by David Flanagan.

 

The options include the following features:

 

height              dimensions of the new window

width

 

left                   the location, across and down, from the upper left of the screen

top                               to the upper left corner of the window

 

and many other features.

 

JUST COPY THE BOLD FACE CODE TO THE BLACKBOARD

( other code is essentially unchanged )

 

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<!--

  by Ira Oldham

-->

<html xmlns="http://www.w3.org/1999/xhtml">

  <head>

    <title>

      Window open and close

    </title>

    <link rel="stylesheet" type="text/css" href="sample.css" title="Course Style" />

    <script type="text/javascript" src="sample-3-open-options.js" />

  </head>

  <body>

    <div class="outer-div">

      <h2>Cleo reaching</h2>

      <p>

        The page will open in a new window or tab.<br />

        <a href="javascript:newWindow();">Cleo reaching</a><br />

        <button onclick="closeWindow();">close the Cleo window</button>

      </p>

    </div>

 

 

      <div id="functions">

 

      <span id="pre_intro">A copy of the JavaScript functions in the head element:</span>

 

      <pre>

 

// sample-3-open-options.js

// This sample shows opening and closing a window

 

// global variable for the new window object

var winObj;

 

// open a new window with cleo.html

function newWindow()

  {

  var features = "height=394,width=288,top=394,left=288,resizable=yes";

  winObj = open("cleo.html", "cleoPage", features);

  }

 

// close the new window

function closeWindow()

  {

  winObj.close();

  }

 

      </pre>

 

    </div>

 

  </body>

</html>

 

Note that the features are coded with comma separators, and no spaces.

 

Automatic closing window

 

McDuffie shows a window that uses a timer to close the window.

In the function that opens the window, she puts:

 

news = open("news.html", "news_window_name");

setTimeout("news.close()", "20000");

 

 

***********************************************************

Writing to windows dynamically

 

Dynamic web pages are a very important part of commercial web sites today.

There are two important technologies used to create dynamic content in web pages.

Both are based on JavaScript.

 

The first is dynamically writing to a web page, using JavaScript and the Document Object Model; this is what we will look at here.

This topic is a large advanced JavaScript topic.  We will look at a little of it.

 

The second is AJAX, which combines the previous dynamically written page technologies with the new XMLHttp protocol.  The XMLHttp protocol allows the transfer of data from the server, without loading a new page.  Then this new data can be dynamically written to the existing page, without reloading the page.

This is a cool new technology that is just recently taking off.

I think we will see major new developments, using this technology, in the next few years.

 

Key to dynamic web pages:

We dynamically change the contents of a page by changing the data in the Document Object Model.  The page and the DOM are tied together, so when we change one, the other also changes.

 

Example of using writeln() to write the contents into an empty page

 

We are in our main window.  We wish to open a pop-up window, and write the html page into the pop-up window.

 

// sample-4-write.js

// This sample shows writing a window

 

// global variable for the new window object

// so we can use it in the

//   newWindow and closeWindow() functions

 

var winObj;

 

function newWindow(my_button_number)

  {

  // open the new window

  // empty string for the page name

  //   means we get an empty window. 

  // We will write the html.

 

  winObj = open("", "writePage", my_features);

 

Now we have a new window.  The variable winObj contains a reference to our new window.  It has nothing in it.  We need to write the whole html page from

<html> to </html>

To do this we will set up three working variables to contain the strings to be written into the new window.

 

  var my_begin = "<html><head><title>show number</title></head><body>";

  var my_text  = "The button you pressed is: ";

  var my_end   = "</body></html>";

 

writeln() is a method of the document object.

writeln() is the same as write() except it puts \n at the end of the line.

So we can write these three strings, and my_button_number

into the new page.

( my_button_number is passed to the newWindow() function as a parameter. )

 

    winObj.document.writeln(my_begin);

    winObj.document.writeln(my_text);

    winObj.document.writeln(my_button_number);

    winObj.document.writeln(my_end);

 

That is all there is to it.  We just wrote all the html tags and the text.

 

Of course we need a closeWindow() function too.

 

function closeWindow()

  {

  winObj.close();

  }

 

I have this code in sample 4 for this unit in the on-line material.

I have some buttons that call the newWindow() function, and pass the number of the button, which is displayed in the new window.

I have a button to close the pop-up window.

 

I wanted to close the pop-up window when the main page closed, even If the user had not clicked the close button.  I did this in the main page with:

 

  <body onunload="closeWindow();">

 

Also:

I did not want to open a window, when the pop-up window was already open.

I did not want to close a window, when the pop-up window was not open.

So, I added the following test with the open:

 

  // if the window does not exist, or is closed, open it

  if( typeof(winObj) == "undefined"  ||  winObj.closed )

    {

    winObj = open("", "writePage", my_features);

    }

 

And, I added the following test with the close:

 

  // if the window exists and is open, close it

  if( typeof(winObj) != "undefined"  && ! winObj.closed )

    {

    winObj.close();

    }

 

In this code, I test to see if the winObj exists first, before testing to see if it is open.

 

I had one more problem.  If the code clicked another numbered button, it did not open a new window, but it did write in the existing window, so the messages kept appending one after another.  I only wanted one message; the last button clicked.

 

You can erase all the old page content by using the document open() method.

Note that previously used the window open() method;

this time we are using the document open() method.

 

    // document open will erase the previous contents of the window

    winObj.document.open();

    winObj.document.writeln(my_begin);

    winObj.document.writeln(my_text);

    winObj.document.writeln(my_button_number);

    winObj.document.writeln(my_end);

    // document close must be used after document open and the write statements

    winObj.document.close();

 

There is still one more thing.  When we open a new window, it is automatically given focus, which brings it up to the top, so it can be seen.  When we write to an existing window, it is not given focus, and is on the bottom, behind the other window, where it cannot be seen.  We fix this by giving it focus:

 

    // if we are writing into an existing window, we must be sure it has focus

    winObj.focus();

 

Finally, I think I have shown you all the JavaScript that is in sample 4 for this unit.

 

How do you find all this stuff?

1) Test your pages carefully.  Look for unusual possible user actions.

2) Read books.  See what fixes the authors use for problems they have found.

 

Example of using the screen object to center the window in the screen

 

// One of the properties of the window is the screen it is

within

  // Use the screen and window properties to compute the

position for the window, to center it in the screen

  // If the window is smaller than the screen, put the

window in the top left

  // This code is somewhat similar to McDuffie Script 11.13

 

  // One of the properties of the window is the screen it

is within

  // Use the screen and window properties to compute the

position for the window, to center it in the screen

  // If the window is smaller than the screen, put the

window in the top left

  // This code is somewhat similar to McDuffie Script 11.13

 

  var my_width  = 250;

  var my_height = 300;

  // Position across from the left

  var xPos = screen.availWidth > my_width ? screen.availWidth/2 - my_width/2 : 0 ;

  // Position down from the top

  var yPos = screen.availHeight > my_height ? screen.availHeight/2 - my_height/2 : 0 ;

 

  // html text to be written into the new page

  var my_begin = "<html><head><title>show number</title></head><body>";

  var my_text  = "The button you pressed is: ";

  var my_end   = "</body></html>";

  var my_features = "height=" + my_height;

  my_features += ",width=" + my_width;

  my_features += ",top=" + yPos;

  my_features += ",left=" + xPos;

  my_features += ",resizable=yes";

 

winObj = open("", "writePage", my_features);

 

 

***********************************************************

Summary

 

You can open and close windows from your JavaScript code.

You can use the Document Object Model to understand, and change the window and the html page.