Even with the advent of the screen object, this can't be used reliably to determine the actual size of the browser window. It is important to know the exact width and height (to the pixel) of the browser to give us the ability to generate layers based on these values. We can use those value to generate layers that stretch to the width of the browser, center layers, or right align them etc., thus giving layers extra flexibility even though they are absolutely positioned.
The best way that I know to find the width/height of the browser is by checking the following properties after the BODY tag. You must place whatever code that is dependent on the width/height in SCRIPT located after the body because in IE the body element is used:
In Netscape:
window.innerWidth window.innerHeight
In IE:
document.body.scrollWidth document.body.scrollHeight
However, these values don't take into consideration the scrollbar. Usually you'll only be concerned about the vertical scrollbar, so you can manually account for it by subtracting 20 from the width in IE, and 16 in Netscape (Netscape excludes the chrome window border).
<BODY> <SCRIPT LANGUAGE="JavaScript"> ns4 = (document.layers)? true:false ie4 = (document.all)? true:false if (ns4) { winW = window.innerWidth-16 winH = window.innerHeight } if (ie4) { winW = document.body.offsetWidth-20 winH = document.body.offsetHeight } // write out the layers accordingly using the CSS function.... </SCRIPT> <!-- other HTML elements go here --> </BODY>
Note: this is the only situation where you should ever have to write CSS within the body.
At any time after the winW and winH variables have been defined can they be used (eg. init() function can use them)
To use these values to center a layer you can do a little math to find where the left/top co-ordinate should be. For example if your layer is 100px wide and 50px tall, you'll need to use the (winW-100)/2 for the left coordinate, and (winH-50)/2 for the top coordinate.
And that translated into code is:
writeCSS ( css('centerDiv',(winW-100)/2,(winH-50)/2,100,50,'blue') )
You can do similar statements to align a layer to the right or bottom of the screen. The following example places layers in all four corners and the center of the screen.
View widthheight1.html for an example which uses the browser width and height extensively View Source Code
That example also utilizes the Netscape Resize Fix function:
// Netscape Resize Fix if (document.layers) { widthCheck = window.innerWidth heightCheck = window.innerHeight window.onResize = resizeFix } function resizeFix() { if (widthCheck != window.innerWidth || heightCheck != window.innerHeight) document.location.href = document.location.href }
This piece of code can be inserted into pages which suffer the common problem when you resize the Netscape browser, all your layers loose their positioning. That code will reload the page, again using the browser width and height to check if the size has changed.
Home | Next Lesson: Page Templates |