Tuesday, December 30, 2008

Getting available screen space for web pages

One of the most common requirements when creating a web page is to get the
space available in the browser window where the content will be displayed. It is always preferable to fit the content into the available space to prevent scroll bars and reduce the effort required on the part of the user. A number of factors cause variations in
the width and the height available for the content of the web page, some of them
being,

  1. Windows Taskbar
  2. Status bar
  3. Toolbars (for eg., MSN toolbar, Google toolbar etc)

Because the user can have any combination of these things enabled, it is difficult to get the exact space and height available. Add to this the fact that different browsers support different sets of properties of the BOM and even for the common set of properties, they give different meanings. Hence, we need to combine multiple approaches to get the available space so that it works in almost all browsers. The code that will do exactly this is given below :

//Returns an array containing the available width and height
function GetWindowSize()
{
....try
....{
........var myWidth = 0, myHeight = 0;
........if (typeof (window.innerWidth) == 'number')
........{
............//Non-IE
............myWidth = window.innerWidth;
............myHeight = window.innerHeight;
........}
........else if(document.documentElement && (document.documentElement.clientWidth
document.documentElement.clientHeight))
........{
............//IE 6+ in 'standards compliant mode'
............myWidth = document.documentElement.clientWidth;
............myHeight = document.documentElement.clientHeight;
........}
........else if (document.body && (document.body.clientWidth
document.body.clientHeight))
........{
............//IE 4 compatible
............myWidth = document.body.clientWidth;
............myHeight = document.body.clientHeight;
........}
........return new Array(myWidth,myHeight);
....}
....catch (ex)
....{
........return null;
....}
}

The above code should suffice for almost all browsers and different browser versions. It is not advisable to use "Screen.availWidth" and "Screen.availHeight" since it doesn't return the correct values in case the user is using toolbars. I have tested the above code for IE and FireFox with and without toolbars and it worked like a charm.

No comments:

Post a Comment