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?
views:
305answers:
5
+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
2010-03-18 23:24:00
You shouldn't use a browser check like `document.all` instead check that clientWidth is not undefined.
Joel Potter
2010-03-18 23:27:18
@Joel, Why not, can you please contribute your answer. Thanks
dono
2010-03-18 23:47:39
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
2010-03-19 00:04:33
that gives the body height, not the browser height.
vsync
2010-03-23 14:29:52
+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
2010-03-19 00:10:49
body size is not the same as window size, which it the desired one actually.
vsync
2010-03-23 14:29:04
This can be optimized using short circuit operators. ex: `width: window.innerWidth || document.body.clientWidth`
Peter Di Cecco
2010-03-23 14:36:28
@vsync, that is true, but window size is not defined by all browsers. @Peter, good point. I'll update that.
Joel Potter
2010-03-23 14:45:40
+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
2010-03-19 02:41:57
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
2010-03-24 18:54:43