Getting Browser's height and width using Javascript

By: Emiley J.  

Getting the Browser's height and width is quite useful in many circumstances. For example if you are using a google map in your site, you will have to set a height and width for the map object. But the problem is there are so many different types of browsers out there and you don't know which one the end user will be using. Another issue is the height and the width of different laptops and desktops available in the market.

So most probably you are fine tuning your application based on the server or the PC or the laptop that you are using to develop. It will look perfectly fine until one day you decide to demo to your colleagues using a different laptop. All the layouts and alignments will be wrong. This happens if you hard code the height and width of the objects that you require in your site.

The best way for such applications is to get the height and the width of the client dynamically (using javascript) and then setting the height and the width of the objects dynamically. You can use the following javascript example to get the height and the width of the client.

var myWidth;
var myHeight;

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; 

}

In my case I had to use a google map in my site, therefore I used this code and then set the height and the width of the google map dynamically as follows:

Setting the google map height and width Dynamically using Javascript:

document.getElementById("map").style.height = myHeight+'px';
document.getElementById("map").style.width = myWidth+'px';



Archived Comments

1. JasonNix
View Tutorial          By: JasonNix at 2017-04-25 11:45:14

2. Winstonmog
View Tutorial          By: Winstonmog at 2017-04-06 11:08:38

3. Great this script worked for me, i now use it for my site to center vertical ^^
View Tutorial          By: runescape private servers at 2012-10-29 22:47:25

4. Nice.
it's work fine.
Thank you

View Tutorial          By: anand at 2012-07-24 06:27:36

5. I have problem about It. When use combine with jquery mobile. Please help me.
View Tutorial          By: aaaa at 2011-10-17 08:02:10

6. Hi,

I have tried with your script and it works, but not as intended. It returns reall

View Tutorial          By: Ivan at 2011-09-08 21:17:36


Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)

Comment on this tutorial