Opening a Centered Pop-Up Window


newwin.moveTo(   Math.round((screenwidth - windowwidth) / 2),   Math.round((screenheight - windowheight) / 2)); 

Combining the phrases to open a window, determining its dimensions, and repositioning it enable you to create a new window that is centered on the page.

The idea is to calculate the width and height of the new window (remember that window.open() returns a reference to the new window) and then determine the screen size, and from that to calculate the required position of the window so that it is centered.

However, timing is crucial here. On Internet Explorer you can access the window dimensions only after the <body> element has been parsed. Therefore, a small trick is used: First, the new window is empty. Then, document.write() creates a <body> element. Then, the window width and height can be read. Finally, the desired document is loaded in the new window, which is then repositioned to the center of the screen.

Opening and Centering a Window (center.html)

<script language="JavaScript"   type="text/javascript"> var newwin = window.open("", "samsWindow", ""); newwin.document.write("<body></body>"); var windowwidth, windowheight; if (window.innerWidth) {   windowwidth = newwin.outerWidth;   windowheight = newwin.outerHeight; } else {   windowwidth = newwin.document.body.clientWidth;   windowheight = newwin.document.body.clientHeight; } var screenwidth = screen.availWidth; var screenheight = screen.availHeight; newwin.moveTo(   Math.round((screenwidth - windowwidth) / 2),   Math.round((screenheight - windowheight) / 2)); newwin.location.href =   "http://www.samspublishing.com/"; </script> <body></body> 

Note

Sometimes, reading the window properties does not work as planned in Internet Explorer and yields false results. In that case, it is better to set the size of the new window in the window.open() call and then use this (known as true) value to center the new window.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

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