Thursday, June 18, 2009

Knowing browser width and height [for all browsers]

Today, at my work I need to implement java script for a SharePoint web page. First I developed the javascript in simple HTML page and after it is successful running I moved the code to SharePoint page.

In html page, it was working very fine and on the SharePoint page it was not. After some research I found the problem in the line document.documentElement.clientWidth and document.documentElement.clientHeight. I don’t know what the problem with this. I was browsing both HTML page and SharePoint page in the same browser. This behavior is weird.


I researched on the javascript functions and read all the properties available for the document object and below is the code I came up with.

function GetWindowProps() {
            var browserWidth = 0, browserHeight = 0;
            //For checking non-IE browsers Mozilla, Safari, Opera, Chrome.
            if (typeof (window.innerWidth) == 'number') {
                browserWidth = window.innerWidth;
                browserHeight = window.innerHeight;
            //All IE except version 4
            else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {               
                browserWidth = document.documentElement.clientWidth;
                browserHeight = document.documentElement.clientHeight;
            //IE 4
            else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                browserWidth = document.body.clientWidth;
                browserHeight = document.body.clientHeight;

This will give you the correct values and it will work for any browser. How is it?


  1. How 'bout you use JQuery and forget it?

  2. Was there ever a solution or a reason for this behaviour. I also have a problem with height:expression(document.body.clientHeight-82) not working under Sharepoint 2010 (it dit under 2007). It remains a mystery. If at all - is there a JQuery clientside script that auto-adjusts the hieght - please let me know

  3. Found the answer yesterday. I removed the Doctype (XHTML) and set the UX compatibility to IE7. Dont know if the later was needed, but when it worked I was happy it did.