Update for 2017
Originally written in 2009, my answer still holds up, but I want to provide an updated version for 2017. With browsers continuing to behave differently, it's important to ensure cross-browser consistency. The jQuery team does a great job with this, but you don't need to include the entire library. The relevant portion can be found in line 37 of dimensions.js. Here is an extracted and modified standalone version:
function getWidth() {
return Math.max(
document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth
);
}
function getHeight() {
return Math.max(
document.body.scrollHeight,
document.documentElement.scrollHeight,
document.body.offsetHeight,
document.documentElement.offsetHeight,
document.documentElement.clientHeight
);
}
console.log('Width: ' + getWidth() );
console.log('Height: ' + getHeight() );
Original Answer
Since browsers have varying behaviors, it's crucial to test for values and use the correct one. Here's a function that can help:
function getWidth() {
if (self.innerWidth) {
return self.innerWidth;
}
if (document.documentElement && document.documentElement.clientWidth) {
return document.documentElement.clientWidth;
}
if (document.body) {
return document.body.clientWidth;
}
}
And similarly for height:
function getHeight() {
if (self.innerHeight) {
return self.innerHeight;
}
if (document.documentElement && document.documentElement.clientHeight) {
return document.documentElement.clientHeight;
}
if (document.body) {
return document.body.clientHeight;
}
}
You can call these functions in your scripts by using getWidth()
or getHeight()
. If the browser's native properties are not defined, it will return undefined
.