AndyLangton
Get viewport size (width and height) with javascript
While finding out monitor resolution with javascript can be useful for statistics and certain other applications, often the need is to determine how much space is available within the browser window.
Space within the browser window is known as the ‘viewport’ affected by the monitor resolution, how many toolbars are in use within the browser and whether the browser is in full screen or windowed mode.
The method to get this size is different with IE6 and below to Opera and Mozilla and its variants (no surprises there!). Unfortunately, there’s no way to get the viewport information in ‘quirks mode’ with IE6 (see this MSDN article to find out how to ensure standards compliant mode in IE).
The script below will store the viewport width and height in the variables viewportwidth and viewportheight and write them to the page.
<script type="text/javascript">
<!--
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
}
document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');
//-->
</script>