Thursday, 18 June 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.

Solution:

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?

No comments:

Post a Comment