Web dev

Get web page window size with Javascript

It’s difficult to know the exactly window size, because every browser has different way to render the pages.
The code below is compatible with a lot of browser, old version too.

Code

var w = window.innerWidth;
var h = window.innerHeight;

if (document.body && document.body.offsetWidth) {
   w = document.body.offsetWidth; 
   h = document.body.offsetHeight;
}

if (document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetWidth ) { 
   w = document.documentElement.offsetWidth; 
   h = document.documentElement.offsetHeight;
}

if (window.innerWidth && window.innerHeight) { 
   w = window.innerWidth; 
   h = window.innerHeight;
}

Inner / Offset / compatMode

document.body.offsetWidth: returns the innerwidth value from left hand side to the left side of the vertical scrollbar;
document.compatMode: Indicates whether the document is rendered;
window.innerWidth/innerHeight: widht/height of the browser window including, if rendered, the vertical scrollbar.

The use of multiple if is because every browser has different mode to render the page and different scrollbar size, with the code above are covered the most possible options.

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.