6

I would like a method of getting the available window size across multiple browsers without using jQuery/Mootools/any third-party library dependencies. I've done a little research on this but half the things I've come across talk about Netscape Navigator...

Just wondering if someone out there has more recent advice.

  • Well, third party libraries are excellent for reducing development for things like this, which shouldn't take a long time, but it does since JavaScript isn't consistent across all browsers :p I recommend opening up jQuery or Mootools and checking the code it uses (presumably it is safe, cross-browser compatible JavaScript) – Andrew Jackman Feb 12 '11 at 07:41

3 Answers3

8

For modern browsers:

document.documentElement.clientHeight

is all you need.

Steven Vachon
  • 3,814
  • 1
  • 30
  • 30
6

usage

var width = getWindowSize().width;

code

var getWindowSize = (function() {
  var docEl = document.documentElement,
      IS_BODY_ACTING_ROOT = docEl && docEl.clientHeight === 0;

  // Used to feature test Opera returning wrong values 
  // for documentElement.clientHeight. 
  function isDocumentElementHeightOff () { 
      var d = document,
          div = d.createElement('div');
      div.style.height = "2500px";
      d.body.insertBefore(div, d.body.firstChild);
      var r = d.documentElement.clientHeight > 2400;
      d.body.removeChild(div);
      return r;
  }

  if (typeof document.clientWidth == "number") {
     return function () {
       return { width: document.clientWidth, height: document.clientHeight };
     };
  } else if (IS_BODY_ACTING_ROOT || isDocumentElementHeightOff()) {
      var b = document.body;
      return function () {
        return { width: b.clientWidth, height: b.clientHeight };
      };
  } else {
      return function () {
        return { width: docEl.clientWidth, height: docEl.clientHeight };
      };
  }
})();

Note: The dimensions cannot be determined accurately until after the document has finished loading.

from comp.lang.javascript FAQ

gblazex
  • 49,155
  • 12
  • 98
  • 91
4

This is not a perfect solution, but it is lightweight & suitable for most purposes:

var WX,WY;
if( window.innerWidth )
{
    WX = window.innerWidth;
    WY = window.innerHeight;
} else {
    WX = document.body.clientWidth;
    WY = document.body.clientHeight;
}
Littm
  • 4,923
  • 4
  • 30
  • 38
Dave
  • 3,093
  • 35
  • 32