Getting Browser's height and width using Javascript

By: Emiley J. Viewed: 153580 times  Printer Friendly Format    


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';


Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)

Comment on this tutorial

Subscribe to Tutorials

Related Tutorials

Archived Comments

1. Hi,

I have tried with your script a

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

2. I have problem about It. When use combine with jqu
View Tutorial          By: aaaa at 2011-10-17 08:02:10

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

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

4. Great this script worked for me, i now use it for
View Tutorial          By: runescape private servers at 2012-10-29 22:47:25

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

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