Previous Page
Next Page

Moving Windows to a Specified Location

In the last example, the links on the parent page opened and closed the windows in specified places on the screen. In this task, you'll see how to both open and move the window. In the parent page, clicking a link opens a window in a specified spot. You might use this sort of script for a site where you open a variety of windows, and to provide a way to rearrange the windows with just a click.

The script for this example, Script 6.14, builds on the script for the previous task, using the moveTo() method. The code for opening the windows in the corners of the screen is unchanged; we've added code to deal with moving the windows if they are already open and not in the right place. The HTML for the page is virtually unchanged, except for the wording of the links (Figure 6.13).

Script 6.14. If you need to move windows to specified spots, this script does the job.

var newWindow = null;
window.onload = newWinLinks;

function newWinLinks() {
     for (var i=0; i<document.links.length; i++) {
         document.links[i].onclick = chgWindowState;
     }
}

function windowOpen() {
     if (newWindow && !newWindow.closed) {
        return true;
     }
     return false;
}

function chgWindowState() {
     if (this.id == "closeWin") {
        if (windowOpen()) {
           newWindow.close();
        }
        else {
           alert("The window isn't open");
        }
        return false;
     }

     var topPos = (this.id.indexOf("bottom") == -1)? 0 : screen.availHeight-200;
     var leftPos = (this.id.indexOf("Right") == -1) ? 0 : screen.availWidth-300;

     if (windowOpen()) {
        newWindow.moveTo(leftPos,topPos);
     }
     else {
        newWindow = window.open("","newWin", "toolbar,location=yes,width=300, height=200,
left="+leftPos+", top="+topPos);
     }
     return false;
}

Figure 6.13. If windows are already open but not where we now want them, clicking their new placement link moves them to the specified location.


To open and move windows:

1.
if (windowOpen()) {
  newWindow.moveTo(leftPos,topPos);
}



If the window is already open, we do a newWindow.moveTo() and pass in leftPos and topPos, which are defined earlier in the script. That's all there is to it.

2.
else {
  newWindow = window.open("", "newWin","toolbar,location=yes, width=300,height=200,
 left="+leftPos+",top="+topPos);



If the window wasn't open, we open it in the specified location, just like we did in the previous task.

Tips

  • If you want to change a window's dimensions instead of its location, use resizeTo() instead of moveTo().

  • Both the resizeTo() and moveTo() commands can be used on the current windownot just newly opened windows. However, it's been found that visitors to sites hate having their main window moved even more than they hate pop-up windows, so don't do it.



Previous Page
Next Page