My original answer was written in 2009. While it still works, I'd like to update it for 2017. Browsers can still behave differently. I trust the jQuery team to do a great job at maintaining cross-browser consistency. However, it's not necessary to include the entire library. In the jQuery source, the relevant portion is found on line 37 of dimensions.js. Here it is extracted and modified to work standalone:
function getWidth() {_x000D_
return Math.max(_x000D_
document.body.scrollWidth,_x000D_
document.documentElement.scrollWidth,_x000D_
document.body.offsetWidth,_x000D_
document.documentElement.offsetWidth,_x000D_
document.documentElement.clientWidth_x000D_
);_x000D_
}_x000D_
_x000D_
function getHeight() {_x000D_
return Math.max(_x000D_
document.body.scrollHeight,_x000D_
document.documentElement.scrollHeight,_x000D_
document.body.offsetHeight,_x000D_
document.documentElement.offsetHeight,_x000D_
document.documentElement.clientHeight_x000D_
);_x000D_
}_x000D_
_x000D_
console.log('Width: ' + getWidth() );_x000D_
console.log('Height: ' + getHeight() );
_x000D_
Since all browsers behave differently, you'll need to test for values first, and then use the correct one. Here's a function that does this for you:
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;
}
}
Call both of these in your scripts using getWidth()
or getHeight()
. If none of the browser's native properties are defined, it will return undefined
.