Getting Browser's height and width using Javascript

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.

JavaScript Code to get browser height and width

var myHeight;

if( typeof( window.innerWidth ) == 'number' ) {


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

Getting Browser's height and width using Javascript