Tuesday, November 24, 2009

How do I get the browser window size?

To determine the actual size of the browser window, use the following properties:

* in Netscape Navigator 4:
window.innerWidth, window.innerHeight
* in Microsoft Internet Explorer:
document.body.offsetWidth, document.body.offsetHeight

Note that the code that uses document.body.offsetWidth and document.body.offsetHeight must be executed after the browser has parsed the BODY tag.

The following code sets the variables winW and winH to the actual width and height of the browser window, and outputs the width and height values. If the user has an old browser, then winW and winH are set to 630 and 460, respectively.

var winW = 630, winH = 460;

if (parseInt(navigator.appVersion)>3) {
if (navigator.appName=="Netscape") {
winW = window.innerWidth;
winH = window.innerHeight;
}
if (navigator.appName.indexOf("Microsoft")!=-1) {
winW = document.body.offsetWidth;
winH = document.body.offsetHeight;
}
}

document.write(
"Window width = "+winW+""br"
+"Window height = "+winH
)

In your browser, this code produces the following output:
Window width = 1280
Window height = 770

Note that if the above code executes within a frame, it will give you the frame's width and height.

To adjust the width and height values taking into accout the scrollbars:

* in Netscape Navigator: subtract 16 from the width and height
* in Microsoft Internet Explorer: subtract 20 from the width and height

Thus, the code adjusted for scrollbars might look as follows:

if (parseInt(navigator.appVersion)>3) {
if (navigator.appName=="Netscape") {
winW = window.innerWidth-16;
winH = window.innerHeight-16;
}
if (navigator.appName.indexOf("Microsoft")!=-1) {
winW = document.body.offsetWidth-20;
winH = document.body.offsetHeight-20;
}
}