API
@-Formulas
JavaScript
LotusScript
Reg Exp
Web Design
Notes Client
XPages
 
Open Centered Window
There are many times when you want to open a child window on a web page for one reason or another. So I'm sure you're familiar with the JavaScript function window.open which allows a child window to be opened. The function described here takes that standard call one step further and allows the child window to be opened up centered on the user's screen.

To open the child window centered on the user's screen, you make use of the screen class in JavaScript. This class has two properties which return the width and height of the user's screen. You just apply a little math and you can open up the child window centered on the page.

Here's the function:
function openCenteredWindow(url, height, width, name, parms) {
   var left = Math.floor( (screen.width - width) / 2);
   var top = Math.floor( (screen.height - height) / 2);
   var winParms = "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width;
   if (parms) { winParms += "," + parms; }
   var win = window.open(url, name, winParms);
   if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
   return win;
}

The value (screen.width - width) will give you the amount of "white space" around the left and right sides of the child window. Halving that value will distribute that "white space" evenly. Then it's just a matter of building the other parameters for the standard JavaScript function call.

Note that the function call above is set up so only the first three parameters are required. If "name" is not passed in, there will be no name associated with the child window. If "parms" is not passed in, there will be no additional window parameters (like "resizeable" and others).

You could also enhance this function to allow height and width to be percentage values. For example, if you want the window to be one half the screen width, then you could pass in 0.5 for the width. If you would like to do that, then you have to calculate the actual width and height based on the percentages. To do that, add these two lines as the first lines in the function:
   if (height <= 1) { height = Math.floor(screen.height * height); }
   if (width <= 1) { width = Math.floor(screen.width * width); }

If the value passed in is less than or equal to one, the height or width is adjusted to be that percentage of the screen size.