Question: How do I get the browser window size?
Answer: To determine the actual size of the browser window, use the following properties:
window.innerWidth, window.innerHeight
document.body.offsetWidth, document.body.offsetHeight
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:
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:
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;
}
}
Copyright © 1999-2008, JavaScripter.net.