Controlling Windows


Controlling Windows

As we have seen so far, it is easy enough to open and close windows as well as write content to them. There are numerous other ways to control windows. For example, it is also possible to bring a window to focus using the window.focus() method. Conversely, it is also possible to do the opposite using the window.blur() method. This section will demonstrate a few other common methods for moving, resizing, and scrolling windows.

Moving Windows

Moving windows around this screen is possible using two different methods, window.moveBy() and window.moveTo() . The windowBy() method moves a window a specified number of pixels and has a syntax of

  windowname  .moveBy(  horizontalpixels  ,  verticalpixels  ) 

where

  • windowname is the name of the window to move or just window if the main window.

  • horizontalpixels is the number of horizontal pixels to move the window, where positive numbers move the window to the right and negative numbers to the left.

  • verticalpixels is the number of vertical pixels to move the window, where positive numbers move the window up and negative numbers down.

For example, given that a window called myWindow exists,

 myWindow.moveBy(100,100); 

would move the window up 100 pixels and to the right 100 pixels.

If you have a particular position in the screen in mind to move a window to, it is probably better to use the window.moveTo() method, which will move a window to a particular x/y coordinate on the screen. The syntax of this method is

 windowname.moveTo(x-coord, y-coord) 

where

  • windowname is the name of the window to move or window if the main window.

  • x-coord is the screen coordinate on the x axis to move the window to.

  • y-coord is the screen coordinate on the y axis to move the window to.

So given the window called myWindow is on the screen,

 myWindow.moveTo(1,1); 

would move the window to the origin of the screen.

Resizing Windows

In JavaScript, the methods for resizing windows are very similar to the ones for moving them. The method window.resizeBy( horizontal , vertical ) resizes a window by the values given in horizontal and vertical . Negative values make the window smaller, while positive values make it bigger, as shown by the examples here:

 myWindow.resizeBy(10,10);  // makes the window 10 pixels taller and wider myWindow.resizeBy(-100,0); // makes the window 100 pixels narrower 

Similar to the moveTo() method, window.resizeTo( width , height ) resizes the window to the specified width and height indicated.

 myWindow.resizeTo(100,100); // make window 100x100 myWindow.resizeTo(500,100); // make window 500x100 
Note  

In well-behaved JavaScript implementations , it is not possible to resize windows to a very small size , say 1 1 pixels. This could be construed as a security violation.

Scrolling Windows

Similar to resizing and moving, the Window object supports the scrollBy() and scrollTo() methods to correspondingly scroll a window by a certain number of pixels or to a particular pixel location. The following simple examples illustrate how these methods might be used on some window called myWindow :

 myWindow.scrollBy(10,0); // scroll 10 pixels to the right  myWindow.scrollBy(-10,0); // scroll 10 pixels to the left myWindow.scrollBy(100,100);  // scroll 100 pixels to the right and down myWindow.scrollTo(1,1); // scroll to 1,1 the origin myWindow.scrollTo(100,100); // scroll to 100, 100 

Besides the scrollTo() and scrollBy() methods, an older method called simply scroll() is often used. While this method is supposed to be deprecated, many programmers still use it. The syntax itself is identical to the scrollBy() method. The complete syntax for this method can be found in Appendix B.

A complete example presented here can be used to experiment with the various common Window methods that we have encountered in this chapter.

 <<!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>>Common Window Methods<</title>> <<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />> <<script type="text/javascript">> <<!-- var myWindow; function openIt() {  myWindow = open('','mywin','height=300,width=300,scrollbars=yes');  myWindow.document.writeln("<<html>><<head>><<title>>fun<</title>><</head>><<body>>");  myWindow.document.writeln("<<table bgcolor='#ffcc66' border='1'  width='600'>><<tr>><<td>>");  myWindow.document.writeln("<<h1>>JavaScript Window Methods<</h1>><<br />><<br />> <<br />><<br />><<br />><<br />><<br />><<br />><<br />><<br />>");  myWindow.document.writeln("<</tr>><</td>><</table>><</body>><</html>>");  myWindow.document.close();  myWindow.focus(); } function moveIt() {  if ((window.myWindow) && (myWindow.closed == false))  myWindow.moveTo(document.testform.moveX.value, document.testform.moveY.value); }    function scrollIt() {  if ((window.myWindow) && (myWindow.closed == false))     myWindow.scrollTo(document.testform.scrollX.value, document.testform.scrollY.value); }    function resizeIt() {  if ((window.myWindow) && (myWindow.closed == false))     myWindow.resizeTo(document.testform.resizeX.value, document.testform.resizeY.value); }    //-->> <</script>> <</head>> <<body onload="openIt();">> <<h1 align="center">>Window Methods Tester<</h1>> <<hr />> <<form name="testform" id="testform" action="#" method="get">> <<input type="button" value="Open Window" onclick="openIt();" />> <<input type="button" value="Close Window" onclick="myWindow.close();" />> <<input type="button" value="Focus Window" onclick="if (myWindow)  myWindow.focus();" />> <<input type="button" value="Blur Window" onclick="if (myWindow) myWindow.blur();"  />> <<br />><<br />> <<input type="button" value="Move Up" onclick="if (myWindow)   myWindow.moveBy(0,-10);" />> <<input type="button" value="Move Left" onclick="if (myWindow)   myWindow.moveBy(-10,0);" />> <<input type="button" value="Move Right" onclick="if (myWindow)  myWindow.moveBy(10,0);" />> <<input type="button" value="Move Down" onclick="if (myWindow)  myWindow.moveBy(0,10);" />> <<br />><<br />> X: <<input type="text" size="4" name="moveX" id="moveX" value="0" />>  Y: <<input type="text" size="4" name="moveY" id="moveY" value="0" />> <<input type="button" value="Move To" onclick="moveIt();" />> <<br />><<br />> <<input type="button" value="Scroll Up" onclick="if (myWindow)  myWindow.scrollBy(0,-10);" />> <<input type="button" value="Scroll Left" onclick="if (myWindow)  myWindow.scrollBy(-10,0);" />> <<input type="button" value="Scroll Right" onclick="if (myWindow)  myWindow.scrollBy(10,0);" />> <<input type="button" value="Scroll Down" onclick="if (myWindow)  myWindow.scrollBy(0,10);" />> <<br />><<br />> X: <<input type="text" size="4" name="scrollX" id="scrollX" value="0" />>  Y: <<input type="text" size="4" name="scrollY" id="scrollY" value="0" />> <<input type="button" value="Scroll To" onclick="scrollIt();" />> <<br />><<br />> <<input type="button" value="Resize Up" onclick="if (myWindow)  myWindow.resizeBy(0,-10);" />> <<input type="button" value="Resize Left" onclick="if (myWindow)  myWindow.resizeBy(-10,0);" />> <<input type="button" value="Resize Right" onclick="if (myWindow)  myWindow.resizeBy(10,0);" />> <<input type="button" value="Resize Down" onclick="if (myWindow)  myWindow.resizeBy(0,10);" />><<br />> X: <<input type="text" size="4" name="resizeX" id="resizeX" value="0" />>  Y: <<input type="text" size="4" name="resizeY" id="resizeY" value="0" />> <<input type="button" value="Resize To" onclick="resizeIt();" />> <<br />><<br />> <</form>> <</body>> <</html>> 

Setting Window Location

It is often desirable to set a window to a particular URL. There are numerous ways to do this in JavaScript, but the best way is to use the Location object that is within Window . The Location object is used to access the current location (the URL) of the window. The Location object can be both read and replaced , so it is possible to update the location of a page through scripting. The following example shows how a simple button click can cause a page to load.

 <<form action="#" method="get">>   <<input type="button" value="Go to Yahoo"              onclick="window.location='http://www.yahoo.com';" />> <</form>> 

It is also possible to access parsed pieces of the Location object to see where a user is at a particular moment, as shown here:

 alert(window.location.protocol); // shows the current protocol in the URL alert(window.location.hostname); // shows the current hostname 

The properties of the Location object, which are listed in Appendix B, are pretty straightforward for anyone who understands a URL. Besides setting the current address, we can also move around in the window s history from JavaScript.

Accessing a Window s History

When users click their browser s Back or Forward button, they are navigating the browser s history list. JavaScript provides the History object as a way to access the history list for a particular browser window. The History object is a read-only array of URL strings that show where the user has been recently. The main methods allow forward and backward progress through the history, as shown here:

 <<a href="javascript: window.history.forward();">>Forward<</a>> <<a href="javascript: window.history.back();">>Back<</a>> 
Note  

You should be careful when trying to simulate the Back button with JavaScript, as it may confuse users who expect links in a page labeled back not to act like the browser s Back button.

It is also possible to access a particular item in the history list relative to the current position using the history.go() method. Using a negative value moves to a history item previous to the current location, while a positive number moves forward in the history list. For example:

 <<a href="javascript: window.history.go(-2);">>Back two times<</a>> <<a href="javascript: window.history.go(3);">>Forward three times<</a>> 

Given that it is possible to read the length of the history[] array using the history.length property, you could easily move to the end of the list using

 <<a href="javascript: window.history.go(window.history.length-1));">>Last Item <</a>> 

Controlling the Window s Status Bar

The status bar is the small text area in the lower-left corner of a browser window where messages are typically displayed indicating download progress or other browser status items. It is possible to control the contents of this region with JavaScript. Many developers use this region to display short messages. The benefit of providing information in the status bar is debatable, particularly when you consider the fact that manipulating this region often prevents default browser status information from being displayed ”information that many users rely upon.

The status bar can be accessed through two properties of the Window object: status and defaultStatus . The difference between these two properties is how long the message is displayed. The value of defaultStatus is displayed any time nothing else is going on in a browser window. The status value, on the other hand, is transient and is displayed only for a short period as an event (like a mouse movement) happens. This short example shows some simple status changes as we roll over a link:

 <<a href="http://www.yahoo.com"    onmouseover="window.status='Don\'t Leave Me!'; return true;"    onmouseout="window.status=''; return true;">> Go to Yahoo!<</a>> 

Notice the requirement to return a true value from the event handlers, as the browser will kill the status region change without it. Setting the default browser status value is also very easy. Try adding the following to your page:

 <<script type="text/javascript">> <<!--   defaultStatus='JavaScript is fun!'; //-->> <</script>> 
Note  

Be aware that users may not see the status bar. In many browsers, it is off by default. Also when you are testing these scripts, you need to make sure to try them using an external browser, as many Web editors such as Dreamweaver or Homesite will likely mask the status bar to the editor when using an internal browser.

Setting Window Timeouts and Intervals

The Window object supports methods for setting timers that we might use to perform a variety of functions. These methods include setTimeout() and clearTimeout() . The basic idea is to set a timeout to trigger a piece of script to occur at a particular time in the future. The general syntax is

 timerId =  setTimeout  (script-to-execute, time-in-milliseconds); 

where script-to-execute is a string holding a function call or other JavaScript statement and time-in-milliseconds is the time to wait before executing the specified script fragment. Notice that the setTimeout() method returns a handle to the timer that we may save in a variable, as specified by timerId . We might then clear the timeout (cancel execution of the function) later on using clearTimeout(timerId) . The following example shows how to set and clear a timed event:

 <<!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>>5,4,3,2,1...BOOM<</title>> <<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />> <</head>> <<body>> <<h1 align="center">>Browser Self-Destruct<</h1>> <<hr />> <<div align="center">> <<form action="#" method="get">>    <<input type="button"          value="Start Auto-destruct"          onclick="timer = setTimeout('window.close()', 5000);  alert('Destruction in 5 seconds'); return true;" />>   <<input type="button" value="Stop Auto-destruct"          onclick="clearTimeout(timer); alert('Aborted!'); return true;" />> <</form>> <</div>> <</body>> <</html>> 

Together with the status property of the Window object, we might use a timer to create the (overly used) scrolling ticker tape effect. Many people like to make use of this effect to market items or draw attention to the status bar. Although this feature may accomplish that goal, it makes it impossible for the user to utilize the status bar to see URLs of the links out of the page. This result degrades the usability of the page significantly. Also, be aware that some ill-behaved scroller scripts may eventually crash a browser or cause it to run slowly if they don t free memory up.

 <<!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>>Super Scroller<</title>> <<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />> <<script type="text/javascript">> <<!--   var message = "Look down in the status bar. It's a JavaScript gimmick. . ."   var delay = 175;   var timerID;   var maxCount = 0;   var currentCount = 1;   function scrollMsg()    {      if (maxCount == 0)        maxCount = 3 * message.length;      window.status = message;      currentCount++;      message = message.substring(1, message.length) + message.substring(0,1);      if (currentCount >>= maxCount)       {             timerID = 0;             window.status="";             return;        }      else             timerID = setTimeout("scrollMsg()", delay);    } //-->> <</script>> <</head>> <<body onload="scrollMsg();">> <<h1 align="center">>The Amazing Scroller<</h1>> <</body>> <</html>> 

The setInterval() and clearInterval() methods are supported in later browsers such as the 4. x generation and are used to set a timed event that should occur at a regular interval. We might find that using them is a better way to implement our scroller. Here is an example of the syntax of an interval:

 <<script type="text/javascript">> <<!--   timer = setInterval("alert('When are we going to get there?')", 2000); //-->> <</script>> 

This example sets an alert that will fire every two seconds. To clear the interval, you would use a similar method as a timeout:

 clearInterval(timer); 

More details on the syntax of intervals and timers can be found in Appendix B.




JavaScript 2.0
JavaScript: The Complete Reference, Second Edition
ISBN: 0072253576
EAN: 2147483647
Year: 2004
Pages: 209

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