Section 14.4. Opening and Manipulating Windows


14.4. Opening and Manipulating Windows

The Window object defines several methods that allow high-level control of the window itself. The following sections explore how these methods allow you to open and close windows, control window position and size, request and relinquish keyboard focus, and scroll the contents of a window. This section concludes with an example that demonstrates several of these features.

14.4.1. Opening Windows

You can open a new web browser window with the open( ) method of the Window object.

Window.open( ) is the method by which advertisements are made to "pop up" or "pop under" while you browse the Web. Because of this flood of annoying pop ups, most web browsers have now instituted some kind of pop-up-blocking system. Typically, calls to the open( ) method are successful only if they occur in response to a user action such as clicking on a button or a link. JavaScript code that tries to open a pop-up window when the browser first loads (or unloads) a page will fail.

Window.open( ) takes four optional arguments and returns a Window object that represents the newly opened window. The first argument to open( ) is the URL of the document to display in the new window. If this argument is omitted (or is null or the empty string), the window will be empty.

The second argument to open( ) is the name of the window. As discussed later in the chapter, this name can be useful as the value of the target attribute of a <form> or <a> tag. If you specify the name of a window that already exists, open( ) simply returns a reference to that existing window, rather than opening a new one.

The third optional argument to open( ) is a list of features that specify the window size and GUI decorations. If you omit this argument, the new window is given a default size and has a full set of standard features: a menu bar, status line, toolbar, and so on. On the other hand, if you specify this argument, you can explicitly specify the size of the window and the set of features it includes. For example, to open a small, resizeable browser window with a status bar but no menu bar, toolbar, or location bar, you can use the following line of JavaScript:

 var w = window.open("smallwin.html", "smallwin",                     "width=400,height=350,status=yes,resizable=yes"); 

Note that when you specify this third argument, any features you do not explicitly specify are omitted. See Window.open( ) in Part IV for the full set of available features and their names. For various security reasons, browsers include restrictions on the features you may specify. You are typically not allowed to specify a window that is too small or is positioned offscreen, for example, and some browsers will not allow you to create a window without a status line. As spammers, phishers, and other denizens of the dark side of the Web find new ways to spoof users, browser manufactures will place more and more restrictions on the use of the open( ) method.

The fourth argument to open( ) is useful only when the second argument names an existing window. This fourth argument is a boolean value that specifies whether the URL specified as the first argument should replace the current entry in the window's browsing history (TRue) or create a new entry in the window's browsing history (false), which is the default behavior.

The return value of the open( ) method is the Window object that represents the newly created window. You can use this Window object in your JavaScript code to refer to the new window, just as you use the implicit Window object window to refer to the window within which your code is running. But what about the reverse situation? What if JavaScript code in the new window wants to refer back to the window that opened it? The opener property of a window refers to the window from which it was opened. If the window was created by the user instead of by JavaScript code, the opener property is null.

14.4.2. Closing Windows

Just as the open( ) method opens a new window, the close( ) method closes one. If you create a Window object w, you can close it with:

 w.close( ); 

JavaScript code running within that window itself can close it with:

 window.close( ); 

Note the explicit use of the window identifier to distinguish the close( ) method of the Window object from the close( ) method of the Document object.

Most browsers allow you to automatically close only those windows that your own JavaScript code has created. If you attempt to close any other window, the request either fails or the user is presented with a dialog box that asks him to confirm (or cancel) that request to close the window. This precaution prevents inconsiderate scripters from writing code to close a user's main browsing window.

A Window object continues to exist after the window it represents has been closed. You should not attempt to use any of its properties or methods, however, except to test the closed property; this property is true if the window has been closed. Remember that the user can close any window at any time, so to avoid errors, it is a good idea to check periodically that the window you are trying to use is still open.

14.4.3. Window Geometry

The Window object defines methods that move and resize a window. Using these methods is typically considered very poor form: the user should have exclusive control of the size and position of all windows on her desktop. Modern browsers typically have an option to prevent JavaScript from moving and resizing windows, and you should expect this option to be on in a sizable percentage of browsers. Furthermore, in order to thwart malicious scripts that rely on code running in small or offscreen windows that the user does not notice, browsers usually restrict your ability to move windows offscreen or to make them too small. If, after all these caveats, you still want to move or resize a window, read on.

moveTo( ) moves the upper-left corner of the window to the specified coordinates. Similarly, moveBy( ) moves the window a specified number of pixels left or right and up or down. resizeTo( ) and resizeBy( ) resize the window by an absolute or relative amount. Details are in Part IV.

14.4.4. Keyboard Focus and Visibility

The focus( ) and blur( ) methods also provide high-level control over a window. Calling focus( ) requests that the system give keyboard focus to the window, and calling blur( ) relinquishes keyboard focus. In addition, the focus( ) method ensures that the window is visible by moving it to the top of the stacking order. When you use the Window.open( ) method to open a new window, the browser automatically creates that window on top. But if the second argument specifies the name of a window that already exists, the open( ) method does not automatically make that window visible. Thus, it is common practice to follow calls to open( ) with a call to focus( ).

14.4.5. Scrolling

The Window object also contains methods that scroll the document within the window or frame. scrollBy( ) scrolls the document displayed in the window by a specified number of pixels left or right and up or down. scrollTo( ) scrolls the document to an absolute position. It moves the document so that the specified document coordinates are displayed in the upper-left corner of the document area within the window.

In modern browsers the HTML elements of a document (see Chapter 15) have offsetLeft and offsetTop properties that specify the X and Y coordinates of the element (see Section 16.2.3. for methods you can use to determine the position of any element). Once you have determined element position, you can use the scrollTo( ) method to scroll a window so that any specified element is at the upper-left corner of the window.

Another approach to scrolling is to call the focus( ) method of document elements (such as form fields and buttons) that can accept keyboard focus. As part of transferring focus to the element, the document is scrolled to make the element visible. Note that this does not necessarily put the specified element at the top left of the window but does ensure that it is visible somewhere in the window.

Most modern browsers support another useful scrolling method: calling scrollIntoView( ) on any HTML element to make that element visible. This method attempts to position the element at the top of the window, but it can't do that if the element is near the end of the document, of course. scrollIntoView( ) is less widely implemented then the focus( ) method but works on any HTML element, not just those that can accept keyboard focus. Read more about this method in the HTMLElement section in Part IV.

One final way you can scroll a window under script control is to define anchors with <a name=> tags at all locations to which you may want to scroll the document. Then, use these anchor names with the hash property of the Location object. For example, if you define an anchor named "top" at the start of your document, you can jump back to the top like this:

 window.location.hash = "#top"; 

This technique leverages HTML's ability to navigate within a document using named anchors. It makes the current document position visible in the browser's location bar, makes that location bookmarkable, and allows the user to go back to his previous position with the Back button, which can be an attractive feature.

On the other hand, cluttering up the user's browsing history with script-generated named anchors could be considered a nuisance in some situations. To scroll to a named anchor without (in most browsers) generating a new history entry, use the Location.replace( ) method instead:

 window.location.replace("#top"); 

14.4.6. Window Methods Example

Example 14-4 demonstrates the Window open( ), close( ), and moveTo( ) methods and several other window-programming techniques discussed in this chapter. It creates a new window and then uses setInterval( ) to repeatedly call a function that moves it around the screen. It determines the size of the screen with the Screen object and then uses this information to make the window bounce when it reaches any edge of the screen.

Example 14-4. Creating and manipulating windows

 <script> var bounce = {     x:0, y:0, w:200, h:200,  // Window position and size     dx:5, dy:5,              // Window velocity     interval: 100,            // Milliseconds between updates     win: null,                // The window we will create     timer: null,              // Return value of setInterval( )     // Start the animation     start: function( ) {          // Start with the window in the center of the screen          bounce.x = (screen.width - bounce.w)/2;          bounce.y = (screen.height - bounce.h)/2;          // Create the window that we're going to move around          // The javascript: URL is simply a way to display a short document          // The final argument specifies the window size          bounce.win = window.open('javascript:"<h1>BOUNCE!</h1>"', "",                                   "left=" + bounce.x + ",top=" + bounce.y +                                   ",width=" + bounce.w + ",height=" +bounce.h+                                   ",status=yes");          // Use setInterval( ) to call the nextFrame( ) method every interval          // milliseconds. Store the return value so that we can stop the          // animation by passing it to clearInterval( ).          bounce.timer  = setInterval(bounce.nextFrame, bounce.interval);     },     // Stop the animation     stop: function( ) {          clearInterval(bounce.timer);                // Cancel timer          if (!bounce.win.closed) bounce.win.close( ); // Close window     },     // Display the next frame of the animation.  Invoked by setInterval( )     nextFrame: function( ) {          // If the user closed the window, stop the animation          if (bounce.win.closed) {              clearInterval(bounce.timer);              return;          }          // Bounce if we have reached the right or left edge          if ((bounce.x+bounce.dx > (screen.availWidth - bounce.w)) ||              (bounce.x+bounce.dx < 0)) bounce.dx = -bounce.dx;          // Bounce if we have reached the bottom or top edge          if ((bounce.y+bounce.dy > (screen.availHeight - bounce.h)) ||              (bounce.y+bounce.dy < 0)) bounce.dy = -bounce.dy;          // Update the current position of the window          bounce.x += bounce.dx;          bounce.y += bounce.dy;          // Finally, move the window to the new position          bounce.win.moveTo(bounce.x,bounce.y);          // Display current position in window status line          bounce.win.defaultStatus = "(" + bounce.x + "," + bounce.y + ")";     } } </script> <button onclick="bounce.start( )">Start</button> <button onclick="bounce.stop( )">Stop</button> 




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net