Wednesday, 9 December 2009

Get the size of the window cross-browser way

Hello everyone!

I'm sorry for a little bloggin break, but just because there are only few visitors that read this blog, so I guess it makes it ok then :)

Today I will spread a little knowledge about cross-browser window properties. The example how this system works is here, feel free to copy-paste the code if needed. You can also try this example in different browsers, this works even in IE5 and IE6 :))) Drag the window to see data changing.

Every webdeveloper has come to a situation when he/she needs to get the height and width of the window area. This seems quite a simple task if you check the W3C recomendations, however it becomes more difficult when you try to implement it.
The difficulty lies in cross-browser implementation. W3C tells us to use this:
for height:
var height_of_the_window = window.outterHeight;
for width:
var width_of_the_window = window.outterWidth;

I have to say, it works great in Mozzila, Google "Chrome" and Safari, however The Microsoft Internet Explorer does not give any sign of beeing alive this way.
What Microsoft specialists give us is:
for height:
var height_of_the_window = document.body.clientHeight;
for width:
var width_of_the_window = document.body.clientWidth;
So now we have 2 ways of getting the size of the window. However, I was searching the internet for even more ways of how to get it and I found that you can get/set the size of the window, by doing this ( believe me, I don't get it when and how it works):
for height:
var height_of_the_window = document.documentElement.clientHeight;
for width:
var width_of_the_window = document.documentElement.clientWidth;

So basically if you don't want to write a long function for different browsers to find/set the size of the window, you can simply use my tip:
declare height and width variables consisting all of these methods!
So actually you can do it like this:

function get_window_size(){
var height_of_the_window = window.outerHeight || document.body.clientHeight || document.documentElement.clientHeight;
var width_of_the_window = window.outerWidth || document.body.clientWidth || document.documentElement.clientWidth;
}

The sign || in javascript means "or", so actually this sentence goes like this:
The height of this window is: the mozilla way or microsoft internet explorer way or some other way.
So actually by doing this, you admit, that your variables might differ in different browsers and by doing this you can create powerfull cross-browser applications.

Hope, you enjoyed reading this,
Cheers!

No comments:

Post a Comment