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: Window width = 1440 Window height = 789
Notes:
- If the above code executes within a frame or iframe, it will give you the frame’s width and height.
- 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.
- The code that uses document.body.offsetWidth and offsetHeight should be executed after the browser has parsed the tag.
- If the user resizes the browser window, you may need to recompute the width and height (use window.onresize to do so).
- Similarly, if the user zooms in (or zooms out) you may also need to recompute the width and height.
Hello! I am Narayanaswamy founder and admin of narayanatutorial.com. I have been working in the IT industry for more than 12 years. NarayanaTutorial is my web technologies blog. My specialties are Java / J2EE, Spring, Hibernate, Struts, Webservices, PHP, Oracle, MySQL, SQLServer, Web Hosting, Website Development, and IAM(ForgeRock) Specialist
I am a self-learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.