He has all the virtues I dislike and none of the vices I admire.
Sir Winston Churchill (1874-1965)
While finding out monitor resolution with javascript can be useful for statistics and certain other applications, often the need is to determine how much space is available within the browser window.
Space within the browser window is known as the 'viewport' affected by the monitor resolution, how many toolbars are in use within the browser and whether the browser is in full screen or windowed mode.
The method to get this size is different with IE6 and below to Opera and Mozilla and its variants (no surprises there!). Unfortunately, there's no way to get the viewport information in 'quirks mode' with IE6 (see this article to find out how to ensure standards compliant mode in IE).
The script below will store the viewport width and height in the variables viewportwidth and viewportheight and write them to the page.
<script type="text/javascript">
<!--
var viewportwidth;
var viewportheight;
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
if (typeof window.innerWidth != 'undefined')
{
viewportwidth = window.innerWidth,
viewportheight = window.innerHeight
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth !=
'undefined' && document.documentElement.clientWidth != 0)
{
viewportwidth = document.documentElement.clientWidth,
viewportheight = document.documentElement.clientHeight
}
// older versions of IE
else
{
viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
viewportheight = document.getElementsByTagName('body')[0].clientHeight
}
document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');
//-->
</script>
Various commenters have proposed shortened versions of the code.
As a function (thanks to Bryan Price):
<script type="text/javascript">
<!--
function viewport()
{
var e = window
, a = 'inner';
if ( !( 'innerWidth' in window ) )
{
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] }
}
//-->
</script>
Just return variables (thanks to elstcb). This leaves the width in variable x and the height in variable y.:
<script type="text/javascript">
<!--
var w=window,d=document,e=d.documentElement,g=d.getElementsByTagName('body')[0],x=w.innerWidth||e.clientWidth||g.clientWidth,y=w.innerHeight||e.clientHeight||g.clientHeight;
//-->
</script>
12.04.2007. 19:27
Ferry Meidianto said on 05.05.2007. 12:38
Thanks. It's fully help me.
Jonathan Rochkind said on 04.09.2007. 19:11
Hmm, it seems to not work in an IE6 window in standards compliant mode, if the window has a frameset in it? I can't figure out what's going on.
Escoffie said on 28.10.2007. 20:56
That's great! Just what I needed.
Question: It is possible to update this when the user changes the viemport size? Because it seems that works only on load.
Andy said on 30.10.2007. 21:04
You can use window.onresize to trigger the check - I would wrap the original in a function first.
Christian said on 14.11.2007. 10:46
one problem still remains: if you are in an iframe that is, lets say 2000px high (at least higher than your browser window) how can you find out how high the visible area is? any ideas?
cheers,
Christian
Khurram Adeeb Noorani said on 01.01.2008. 08:06
Works fine in Firefox but doesn't work in IE-7 ... following error occured when i executed this code in IE-7
document.getElementsByTagName(...)[0].clientWidth is null or not an object
could u plz fix it ??
Niyaz PK said on 16.01.2008. 06:23
Thanks for the code.
I will probably use this code for an app in my site.
alohci said on 14.02.2008. 00:49
This is good, but there's a trap in Opera 9 to watch out for. If the user zooms the page, Opera uses two different pixel sizes. clientWidths are measured in virtual pixels, innerWidth in real pixels. [Presumably ditto for Heights but I haven't checked] So, depending on what you are using the Viewport size for, the measurements may not be comparible.
Aleksandar said on 05.03.2008. 13:49
document.documentElement.clientWidth in IE6 does not work properly. It includes the size of the vertical scrollbar which is always visible, thus making this value unusable for setting an element width that should span entire viewport.
I don't have a solution for that yet.
Samir said on 11.06.2008. 08:41
Guys, anyone knows how to get thw whole window size (Not just the content area) in Safari and FireFox? I managed to get it working in IE and Opera!!!
Any help is greatly appreciated
Andy said on 12.06.2008. 18:49
When you say window size, do you mean including the browser 'chrome'?
Bryan Price said on 20.06.2008. 22:08
This would be shorter:
function viewport()
{
var e = window
, a = 'inner';
if ( !( 'innerWidth' in window ) )
{
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] }
}
Chiranjeevi said on 23.06.2008. 07:04
WOW It really Helped me i have no problems with mozilla but IE is pulling me back to some other methods which are still confusion. Really It has worked.
Thanks Very much
Chris said on 02.08.2008. 21:40
re Christian (iframe question): I think you need to get into the parent document (window.parent I believe) and get the width and height of the iframe element. I.e., you don't need this script in that case.
Rex said on 21.08.2008. 16:40
great! excatly what I was looking for! thanks a lot
rich said on 19.11.2008. 14:01
hi, there is a split second in ie7 where toggle elements show b4 code is fully loaded is there any way to avoid this happening by modifying your javascript?
wheat said on 25.11.2008. 14:27
Perfect! Really helped me out. Thanks.
The Loud Ninja said on 10.01.2009. 00:56
Thank you, thank you, thank you! Trying to figure out the canvas width and height in different browsers is such a *royal* pain. Your script has been a lifesaver many times.
paulr said on 20.01.2009. 07:16
hi. i'm trying to position a horizontal menu at the bottom of the viewport... which i can do, so long as the horizontal scroll bar doesn't appear.
every variable i've tried to use to determine the screen height does not seem to consider the possible presence of the scroll bar. i.e. the value doesn't change when a screen is narrowed and a scroll bar appears.
is there someway to determine viewport height MINUS the scrollbar height???
many tkx...
--paul
Shibaram said on 17.02.2009. 18:54
How can I use this to get the viewport in frames based windows ?
Because I need to show a div in content frame, (this frame only acquires 1/4 of the total screen in center part)
How can I place a div exactly in center of all frames ?
Kyle Simpson said on 22.02.2009. 20:14
I use a different approach, which works in IE6 too. I instantiate an invisible (visibility:hidden) element (div, for instance), and set it position:fixed at 0,0 and width/height of 100%. Actually, for IE quirks, to emulate position:fixed, I use CSS expressions. Anyway, this gives the viewport size (unless the page is too short, which I correct for in other various ways).
imitation said on 31.05.2009. 18:35
Thanks a lot!
This helps me (and clients) save a lot of bandwidth by automagically scaling down the background image on the server to suit the viewport size!
KGTM said on 18.07.2009. 20:15
Works on Firefox 3.5, Google Chrome, Safari and Opera.
For some reason he doesn't write the document.write action and prints the size values.
MikhailValerie said on 24.07.2009. 01:51
function viewPort() {
var h = window.innerHeight || document.documentElement.clientHeight || document.getElementsByTagName('body')[0].clientHeight;
var w = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;
return { width : w , height : h }
}
alert('h: ' + viewPort().height + '\r\nw: ' + viewPort().width);
Tested in IE8, FF 3.5, Safari, Opera, Chrome
shaahin said on 20.09.2009. 17:19
tnx! this really helped me! :D
framer said on 22.09.2009. 06:33
if this code is run inside an iframe, it wouldn't be able to get the browser size of hosting page.
Fipo said on 21.10.2009. 22:29
Greetings ;)
Thanks a lot about this article.
It's very useful ...
(bow)
objector.L said on 31.10.2009. 14:52
Nice article! cross-browser code should be like this. That's very useful for me!
Anoop said on 01.12.2009. 08:39
pls help me with this... in IE7 and later versions, if document size less than viewport size, this code returns document size. is there a way to get actual viewport size in this case?
bjornson said on 08.12.2009. 08:48
To get the real viewport dimensions that also takes into account the size of scrollbars and works on most browsers in a simple way you should just use jquery and at any point where you need the size you use:
$(window).height()
and
$(window).width()
this just saved me a lot of time!
$(window).width() and $(window).height() shows me only the function that creates it and not numbers. whats wrong?
heres my code, triggered on window resize using jquery:
$(window).resize(function(event){
var width=$(window).width;
alert(width);
})
Vacheslav said on 25.01.2010. 12:57
Yes, it works!!
BTW, MSDN article You reffered to isn't available at present.
g@miernicki.com said on 01.02.2010. 00:10
awesome! this is by far the best method ive come across to do this to date!
CHEERS!
Chetan Crasta said on 23.03.2010. 08:51
Nice script. Thanks for sharing!
DOUG LUBEY OF LOUISIANA said on 15.04.2010. 03:03
thanks. BUT A FRIENDLY NOTE:
'px' is required for FIREFOX to resize an element
// px is very important for FIREFOX; it will not resize if px is not included
// -25 is so that we can have a real SMALL border around the FLASH object
document.getElementById("panShowCourseWindow").style.height = (viewportheight - 25) + 'px';
=====HTML CODE TO REFERENCE
Yorkshire Web Design said on 01.05.2010. 15:36
Excellent works a treat. Thanks for sharing! Ted
Alex Stanhope said on 21.05.2010. 07:01
Joe, you're referencing the element but not calling the function:
$(window).resize(function(event){
var width=$(window).width;
alert(width);
})
should be
$(window).resize(function(event){
var width=$(window).width();
alert(width);
})
notice brackets after width.
Cheers, Alex
Thany said on 17.06.2010. 14:36
viewportwidth = window.innerWidth,
viewportheight = window.innerHeight
This is not right, it should be:
viewportwidth = window.innerWidth;
viewportheight = window.innerHeight;
Otherwise you'll get script errors/warnings.
Robert Bravery said on 23.07.2010. 09:31
This is very nice. This was giving me a headache until I found this script.
Works fantastic.
Golden Eagle said on 29.07.2010. 19:01
@Escoffie : What you need is few lines of AJAX(& some kind of timer which checks for viewport changes at regular intervals).
Check AJAX tutorials
emjay said on 15.09.2010. 13:44
I have found that you can use
document.getElementsByTagName('body')[0].clientWidth
on ALL modern browsers and it gives the correct result.
Anemo Form & Funktion said on 08.10.2010. 17:32
This was exactly what I was looking for!
Very useful for setting viewport height to a wrapper div for instance. Just put the script before and use the following to print out the css-code:
document.write('#your-wrapper { height: '+viewportheight+'px; }');
Thanks alot!
Will said on 25.11.2010. 14:41
Fantastic - just what I was after.
Matthieu said on 03.01.2011. 10:31
function toggle3(biggerbigbox)
{
var biggerbig=document.getElementById(biggerbigbox);
biggerbig.style.width=(biggerbig.style.width=='90px')?'+viewportwidth++px':'90px';
biggerbig.style.height=(biggerbig.style.height=='90px')?'+viewportheight++px':'90px';
}
I am using this code to toggle boxes from 90px X Y to any bigger size.. I want to use viewportheight and width but i cant seem to find the correct place to add "PX" at without getting or an error, or no result...
Still, it works with a regular div... And i'd like to subtract like 20px on each X and Y so i get a bit of margin...
Any tricks would be well appreciated ^_^
You may contact me with my website's chatbox in the box entitled "chatbox"
I'll also bookmark this page and watch replies! ;)
sztatty said on 05.01.2011. 16:18
Good Job, but my ie gave error with: getElementsByTagName
Saloob said on 07.02.2011. 13:50
Use the following to convert to a php variable;
?>
jurriaan said on 19.02.2011. 12:42
Needs to be in the body section of the html i guess, else it didn't work for me...
Dylan said on 12.03.2011. 06:47
Thank you SOOOOOOOOOO much.
I only needed the height to fully extend nested backgrounds when content is less than viewport.
As in CONTENT
I have tried other solutions, both JS and css including browser-specific stuff...
But this script is the only one that did it all in all browsers.
Thank you SOOOO SOOOO much
Vicious said on 09.04.2011. 13:06
Works in IE8 when I view this page. Copy the code to my own page and I get an error: document.getElementsByTagName(...).0.clientWidth is empty or not an object
Vignesh said on 11.04.2011. 15:40
Hi, Thank you for this script.
And same thing how can i asign the size of webpage. For reverse operation. Thanks.
gonzo said on 06.05.2011. 02:17
Will this ever work if my javascript is loaded inside a cross-domain iframe?
elstcb said on 27.05.2011. 23:47
Thanks for the post, just what I was looking for!
If you don't mind sacrificing readability then MikhailValerie's short version can be reduced even further.
var w=window,d=document,e=d.documentElement,g=d.getElementsByTagName('body')[0],x=w.innerWidth||e.clientWidth||g.clientWidth,y=w.innerHeight||e.clientHeight||g.clientHeight;
Leaves the width in variable x and the height in variable y.
Tested in (Win XP) IE6, IE9; (Win 7) FF3, FF4, Chrome 11, Safari 5, Opera 11
Swapnil Mirkute said on 21.07.2011. 08:06
Thanks for the such a nice post...it has solved my problem.
MartynInManila said on 14.08.2011. 06:53
the perfect ingredient for the sidebar menu where I wanted to determine the inner height to cause an additional element to display or not, thank you
dukanista said on 16.09.2011. 18:20
simply perfect!! is the most compact and readability i've seen. Thanks
Behnam said on 25.09.2011. 15:10
Thanks for the such a nice post...it has solved my problem
GetGoGlobal said on 23.11.2011. 09:45
Thank you very much.
Someone buy this man a drink!
He knows how to write a solid code post. Fixed my issue like a laser.
what i want to know is what is the length of this web page i mean not the screen size/resolution/height etc. but the length of this whole page in pixels.
thanks.
ali
m_online4u@hotmail.com
Timo said on 21.12.2011. 13:12
I get a strange error when trying to receive the width of the browser.
I'm using a VM via RDP with a resolution of 1680x1050. When I want to determine the values with:
width = document.getElementById("editorLoading").offsetWidth;
height = document.getElementById("editorLoading").offsetHeight;
(where editorLoading is a div with 100% width and height), I get a width with 1683px ??!??
jnm2 said on 04.01.2012. 13:13
This way is much faster (no string manipulation) and shorter and does the exact same thing:
function viewport() {
return {width: window.innerWidth || (document.documentElement || document.body).clientWidth, height: window.innerHeight || (document.documentElement || document.body).clientHeight};
}
Page last (manually) updated: October 14, 2011.
Questions, comments, insults or praise? Have your say: