Monday, June 1, 2009

Browser Window size using JavaScript

Determining the size of a window cross-browser is not straightforward. Firefox, Safari, Opera, and Chrome all provide four properties: innerWidth , innerHeight , outerWidth , and outerHeight.

  • Safari and Firefox: outerWidth and outerHeight return the dimensions of the browser window itself.
  • Opera: outerWidth and outerHeight return the size of the page view container.
  • Chrome: outerWidth and outerHeight return the size of the viewport
  • IE: offers no way to get the current dimensions of the browser window; however, it does provide information about the viewable area of the page via the DOM, document.documentElement.clientWidth and document.documentElement.clientHeight.

The document.documentElement.clientWidth and document.documentElement.clientHeight properties provide the width and height of the page viewport in IE, Firefox, Safari, Opera, and Chrome. So, a generalized method for retrieving the browser window width and height is given below:

var pageWidth = window.innerWidth, pageHeight = window.innerHeight;
if (typeof pageWidth != "number"){
    if (document.compatMode == "CSS1Compat"){
        pageWidth = document.documentElement.clientWidth;
        pageHeight = document.documentElement.clientHeight;
    } else {
        pageWidth = document.body.clientWidth;
        pageHeight = document.body.clientHeight;

Technorati Tags:


Thanks a lot for your valuable comments :)