Browser Window Size in JavaScript

JavaScript FAQ | Client & Browser Configuration FAQ  

Question: How do I determine the browser window size in JavaScript?

Answer: To determine the size of the browser window, use the following properties:

  • in Internet Explorer (backward-compatibility mode):
    document.body.offsetWidth, document.body.offsetHeight
  • in Internet Explorer (standards mode, document.compatMode=='CSS1Compat'):
    document.documentElement.offsetWidth, document.documentElement.offsetHeight
  • in most other browsers – as well as IE9 (standards mode):
    window.innerWidth, window.innerHeight (the page's visible width/height)
    window.outerWidth, window.outerHeight (the browser outer width/height)

    The following code sets the variables winW and winH to the inner width and height of the browser window, and outputs the width and height values. If the user has a very old browser, then winW and winH are set to 630 and 460, respectively.

    var winW = 630, winH = 460;
    if (document.body && document.body.offsetWidth) {
     winW = document.body.offsetWidth;
     winH = document.body.offsetHeight;
    }
    if (document.compatMode=='CSS1Compat' &&
        document.documentElement &&
        document.documentElement.offsetWidth ) {
     winW = document.documentElement.offsetWidth;
     winH = document.documentElement.offsetHeight;
    }
    if (window.innerWidth && window.innerHeight) {
     winW = window.innerWidth;
     winH = window.innerHeight;
    }
    
    document.writeln('Window width = '+winW);
    document.writeln('Window height = '+winH);
    

    In your browser, this code produces the following output:

    Notes:
    (1) If the above code executes within a frame or iframe, it will give you the frame's width and height.
    (2) The computed width and height do not include the title bar, menu bar, status bar, or toolbar(s) - but may include the horizontal and vertical scrollbar(s), if any. (The properties outerWidth/outerHeight, unlike others, do return the outside dimensions of the browser window; however, outerWidth/outerHeight are not available in IE8 or earlier.)
    (3) The code that uses document.body.offsetWidth and offsetHeight should be executed after the browser has parsed the <BODY> tag.
    (4) If the user resizes the browser window, you may need to recompute the width and height (use window.onresize to do so).
    (5) Similarly, if the user zooms in (or zooms out) you may also need to recompute the width and height.

  • Copyright © 1999-2011, JavaScripter.net.