Finding Window Dimensions with Javascript

December 13, 2008 · Print This Article

Sometimes you may want to find the dimensions of the user’s browser window. Below is a list of the propertiesthat are accessible with different browsers. Traditionally, window.innerWidth/window.innerHeight is the most widely accepted way to obtain these values, however, there is deviation between IE 4 and IE 6+ in “standards compliant mode.” Below, I have listed the different ways to find the window height and width.
Non-IE Browsers

  • window.innerWidth
  • window.innerHeight

IE 6+ in “standards compliant mode”

  • document.documentElement.clientWidth
  • document.docuementElement.clientHeight

IE 4

  • document.body.clientWidth
  • document.body.clientHeight

Sample code for finding the inner window dimensions
The script below will alert the proper window height and width in various browsers.

function alertSize() {
var myWidth = 0, myHeight = 0;
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;
}
window.alert( 'Width = ' + myWidth );
window.alert( 'Height = ' + myHeight );
}


Your choice for site templates and wordpress themes

Comments

Got something to say?

You must be logged in to post a comment.