views:

305

answers:

5

I'm trying to detect the browser's current size (width and height). I know it's super easy in jquery with $(document).width and $document.height, but I don't want to add the size of the jquery lib to the project, so I'd rather just use built in javascript. What would be the short and efficient way to do the same thing with javascript?

+1  A: 

Try this;

 <script type="text/javascript"> 
winwidth=document.all?document.body.clientWidth:window.innerWidth; 
winHeight=document.all?document.body.clientHeight:window.innerHeight; 
alert(winwidth+","+winHeight);
</script> 
Enrique
You shouldn't use a browser check like `document.all` instead check that clientWidth is not undefined.
Joel Potter
@Joel, Why not, can you please contribute your answer. Thanks
dono
Just because a browser does or does not implement `document.all` does not mean it does or does not implement `document.body.clientHeight`. You should check the property you want, not an unrelated property.
Joel Potter
that gives the body height, not the browser height.
vsync
+4  A: 
// first get the size from the window
// if that didn't work, get it from the body
var size = {
  width: window.innerWidth || document.body.clientWidth,
  height: window.innerHeight || document.body.clientHeight
}
Joel Potter
body size is not the same as window size, which it the desired one actually.
vsync
This can be optimized using short circuit operators. ex: `width: window.innerWidth || document.body.clientWidth`
Peter Di Cecco
@vsync, that is true, but window size is not defined by all browsers. @Peter, good point. I'll update that.
Joel Potter
+2  A: 
function getWindowSize(){
 var d= document, root= d.documentElement, body= d.body;
 var wid= window.innerWidth || root.clientWidth || body.clientWidth, 
 hi= window.innerHeight || root.clientHeight || body.clientHeight ;
 return [wid,hi]
}

IE browsers are the only ones who don't use innerHeight and Width.

But there is no 'standard'- just browser implementations.

Test the html (document.documentElement) clientHeight before checking the body- if it is not 0, it is the height of the 'viewport' and the body.clientHeight is the height of the body- which can be larger or smaller than the window.

Backwards mode returns 0 for the root element and the window (viewport) height from the body.

Same with width.

kennebec
A: 

This post has the script, which has the logic to work with all browsers/ http://praveenbattula.blogspot.com/2009/06/knowing-browser-width-and-height-for.html

Rare Solutions