Find the exact height and width of the viewport in a cross-browser way (no Prototype/jQuery)

Alex Grin picture Alex Grin · Nov 19, 2009 · Viewed 90.7k times · Source

I'm trying to find the exact height and width of a browser's viewport, but I suspect that either Mozilla or IE is giving me the wrong number. Here's my method for height:

var viewportHeight = window.innerHeight || 
                     document.documentElement.clientHeight || 
                     document.body.clientHeight;

I haven't started on width yet but I'm guessing it's going to be something similar.

Is there a more correct way of getting this information? Ideally, I'd like the solution to work with Safari/Chrome/other browsers as well.

Answer

Leo picture Leo · Jan 9, 2010

You might try this:

function getViewport() {

 var viewPortWidth;
 var viewPortHeight;

 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
 if (typeof window.innerWidth != 'undefined') {
   viewPortWidth = window.innerWidth,
   viewPortHeight = window.innerHeight
 }

// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
 else if (typeof document.documentElement != 'undefined'
 && typeof document.documentElement.clientWidth !=
 'undefined' && document.documentElement.clientWidth != 0) {
    viewPortWidth = document.documentElement.clientWidth,
    viewPortHeight = document.documentElement.clientHeight
 }

 // older versions of IE
 else {
   viewPortWidth = document.getElementsByTagName('body')[0].clientWidth,
   viewPortHeight = document.getElementsByTagName('body')[0].clientHeight
 }
 return [viewPortWidth, viewPortHeight];
}

( http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/ )

However, it is not even possible to get the viewport information in all browsers (e.g. IE6 in quirks mode). But the above script should do a good job :-)