Get viewport/window size (width and height) with javascript

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.

The long version

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

The Script in Action

Shorter versions

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>
Category: 

Comments

thanks

thanks

Thanks. It's fully help me.

Thanks. It's fully help me.

This was precisely what I

This was precisely what I have needed! Thanks

Good tip!

Good tip!

Thanks a lot!

Thanks a lot!

Hmm, it seems to not work in

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.

Thanks a Lot

Thanks a Lot

That's great! Just what I

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.

You can use window.onresize

You can use window.onresize to trigger the check - I would wrap the original in a function first.

one problem still remains: if

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

Thanks, it was very userful

Thanks, it was very userful

Just fabulous! been searching

Just fabulous! been searching for this like crazy!

Works fine in Firefox but

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 ??

Thanks for the code.

Thanks for the code.
I will probably use this code for an app in my site.

This is good, but there's a

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.

document.documentElement

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.

Thanks for this. Just what I

Thanks for this. Just what I was after.

Cheers,
Matt

Thanks man!!!!!!

Thanks man!!!!!!

Guys, anyone knows how to get

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

When you say window size, do

When you say window size, do you mean including the browser 'chrome'?

This would be shorter:

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' ] }
}

WOW It really Helped me i

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

re Christian (iframe question

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.

Thanks this helped me out a

Thanks this helped me out a lot.

great! excatly what I was

great! excatly what I was looking for! thanks a lot

Thank you very much! That

Thank you very much! That really helped me a lot!

this code helped me very much

this code helped me very much. thank you for sharing

nice one ;)

nice one ;)

How would you do this to

How would you do this to handle the onresize event?

Good script, highly

Good script, highly functional...exactly what i needed too!!1:)

Perfect! Really helped me

Perfect! Really helped me out. Thanks.

hi. i'm trying to position a

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

How can I use this to get the

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 ?

I use a different approach,

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).

it's works wonderfully...many

it's works wonderfully...many thanks.

Cool,Thank you very much

Cool,Thank you very much

Thanks a lot!

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!

Cool! Thanks!

Cool!
Thanks!

Thanks a million for this!

Thanks a million for this!

thank you very much!

thank you very much!

Works on Firefox 3.5, Google

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.

function viewPort() {

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

@MikhailValerie, thanks for

@MikhailValerie, thanks for the short version!

Really helpful! Thanks!

Really helpful! Thanks!

tnx! this really helped me!

tnx! this really helped me! :D

if this code is run inside an

if this code is run inside an iframe, it wouldn't be able to get the browser size of hosting page.

Woao.... took forever to find

Woao.... took forever to find this...THANK YOU SOO MUCH

Thank you, this is very

Thank you, this is very useful.

Greetings ;)

Greetings ;)
Thanks a lot about this article.
It's very useful ...

(bow)

Pls any one tell me where to

Pls any one tell me where to add these scripts clearly?

Nice article! cross-browser

Nice article! cross-browser code should be like this. That's very useful for me!

Nice code. This is exactly

Nice code. This is exactly what I was searching for.

pls help me with this... in

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?

To get the real viewport

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).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);
})

Vert Thankyou

Vert Thankyou
Vert Thankyou
Vert Thankyou
THANK YOU SOO MUCH
:)

Yes, it works!!

Yes, it works!!
BTW, MSDN article You reffered to isn't available at present.

Thanks.....

Thanks.....
This is exactly what I want.

awesome! this is by far the

awesome! this is by far the best method ive come across to do this to date!

CHEERS!

THANK U :)

THANK U :)

Nice script. Thanks for

Nice script. Thanks for sharing!

great tip! Thanks!

great tip! Thanks!

thanks. BUT A FRIENDLY NOTE:

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

Excellent works a treat.

Excellent works a treat. Thanks for sharing! Ted

Joe, you're referencing the

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

cool and an extension to this

cool and an extension to this

Untitled Document

viewportwidth = window

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.

Thnx man just what i was

Thnx man just what i was looking 4

This is very nice. This was

This is very nice. This was giving me a headache until I found this script.

Works fantastic.

@Escoffie : What you need is

@Escoffie : What you need is few lines of AJAX(& some kind of timer which checks for viewport changes at regular intervals).
Check AJAX tutorials

Lifesaver script! Well done!

Lifesaver script!
Well done!

I have found that you can use

I have found that you can use
document.getElementsByTagName('body')[0].clientWidth
on ALL modern browsers and it gives the correct result.

Thanks It's work man!!!!!!!!!

Thanks It's work man!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

This was exactly what I was

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!

Thank you! This was a true

Thank you! This was a true lifesaver!

Fantastic - just what I was

Fantastic - just what I was after.

thank u so much.. simple but

thank u so much.. simple but very helpful...

function toggle3(biggerbigbox

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! ;)

Good Job, but my ie gave

Good Job, but my ie gave error with: getElementsByTagName

oh, wow, thanks! :)

oh, wow, thanks! :)

Use the following to convert

Use the following to convert to a php variable;

?>

Needs to be in the body

Needs to be in the body section of the html i guess, else it didn't work for me...

Thank you SOOOOOOOOOO much.

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

Works in IE8 when I view this

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

Hi, Thank you for this script

Hi, Thank you for this script.
And same thing how can i asign the size of webpage. For reverse operation. Thanks.

Thanks!

Thanks!

worked like a charm - super

worked like a charm - super stuff guys!

Will this ever work if my

Will this ever work if my javascript is loaded inside a cross-domain iframe?

Thank you very much

Thank you very much

Thanks for the post, just

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

Thnx. You solved the issue in

Thnx. You solved the issue in a hurry

Thanks for the such a nice

Thanks for the such a nice post...it has solved my problem.

the perfect ingredient for

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

simply perfect!! is the most

simply perfect!! is the most compact and readability i've seen. Thanks

Thanks for the such a nice

Thanks for the such a nice post...it has solved my problem

how to set a new width value

how to set a new width value to IE?

Thank you very much.

Thank you very much.

Someone buy this man a drink!

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

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

I get a strange error when

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 ??!??

This way is much faster (no

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

Thanks for these scripts.

Thanks for these scripts. About the html comments inside the script tags ... I ran across a good discussion recommending against that practice, since all browsers now recognize javascript, and there are chances these can create trouble of their own:

http://stackoverflow.com/questions/808816/are-html-comments-inside-scrip...

thanks for this a lot...

thanks for this a lot...

Tnx sir. Finally i got it,

Tnx sir. Finally i got it, now i'm trying to figure out how to add these code into thesis framework :)

Why not just use jquery?

Why not just use jquery?

$(window).width()

very helpful! Thanks a lot.

very helpful! Thanks a lot.

Is there a way to pass these

Is there a way to pass these values of 'x' and 'y' to a php function like:

if x >= 900 {
require_once('xyz.php');
}

just what the doctor order.

just what the doctor order. thankya
you got the credit!

All theres this one:http:/

Thanks a lot, grat code

Thanks a lot, grat code

Forgive a newbie, but those x

Forgive a newbie, but those x and y variables, how can I access them from say php? I do not care to display the width and height, as the long version does, all I want is to get the width of the viewport, so that I can resize a picture properly. How can I get that x and y variables in php?

Thanks!

Forgive a newbie, but those x

Forgive a newbie, but those x and y variables, how can I access them from say php? I do not care to display the width and height, as the long version does, all I want is to get the width of the viewport, so that I can resize a picture properly. How can I get that x and y variables in php?

Thanks!

I am a beginning student in

I am a beginning student in javascript and need a little help. What does the following script do?

var size = 6;
alert(Size);

any help would be appreciated

Gracias por el codigo, me

Gracias por el codigo, me sirvio para resolver el alto de los div e iframe segun la resolucion de pantalla del cliente

Hi,

Hi,

I need to determine the height of the browser and that height needs to be places into the

The Firefox Web Developer

The Firefox Web Developer Toolbar (also available for Chrome) may be useful for testing your site with various viewport sizes.

Thanks. It's fully help me.

Thanks. It's fully help me.

Hi

Hi

I'm quite new to javascript unfortunately and would be grateful for any help. This code is the only one I have found that resizes the index page of my website (with lots of images) to fit the screen of my ipad without cutting off 20px on the side.

However I don't want to have the dimensions written on the page. Is there a way of avoiding this and still have it work? Spent hours on it and can't seem to find a solution.

Thank you!

Add new comment