Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

How can I get windowWidth, windowHeight, pageWidth, pageHeight, screenWidth, screenHeight, pageX, pageY, screenX, screenY which will work in all major browsers?

screenshot describing which values are wanted

share|improve this question
    
i don't know why, you can try this link docs.google.com/… – turtledove Aug 10 '10 at 2:35
150  
Nice pic. All questions should and answers should be like this. – Damien Golding Jun 12 '13 at 8:57
3  
pageHeight(on a pic) u can get with: document.body.scrollHeight – befzz Dec 11 '13 at 20:29
3  
2  
Interesting: ryanve.com/lab/dimensions – ringø Jul 31 '14 at 9:59

11 Answers 11

up vote 602 down vote accepted

If you are using jQuery, you can get the size of the window or the document using jQuery methods:

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document
$(window).width();   // returns width of browser viewport
$(document).width(); // returns width of HTML document

For screen size you can use the screen object in the following way:

screen.height;
screen.width;
share|improve this answer
1  
thanks, and is there any way to get pageX, pageY, screenX, screenY? – turtledove Aug 10 '10 at 2:25
3  
When dealing with mobile Safari, sadly jQuery isn't a perfect solution to this question. See the note on line #13 at github.com/jquery/jquery/blob/master/src/dimensions.js – Joshua Jun 19 '13 at 17:10
4  
@웃웃웃웃웃 what did you edit in the answer? according to the revisions, you didn't edit anything at all – DanFromGermany Jan 28 '14 at 15:31
1  
@mrplants These are all in pixels. – Ankit Jaiswal Apr 14 '14 at 4:43
86  
@pizzaiolaGorgonzola +1, came here looking for vanilla Javascript.. acceped answer is jQ. sigh – Marco Kerwitz Aug 3 '14 at 20:43
function wndsize(){
var w = 0;var h = 0;
//IE
if(!window.innerWidth){
    if(!(document.documentElement.clientWidth == 0)){
        //strict mode
        w = document.documentElement.clientWidth;h = document.documentElement.clientHeight;
    } else{
        //quirks mode
        w = document.body.clientWidth;h = document.body.clientHeight;
    }
} else {
    //w3c
    w = window.innerWidth;h = window.innerHeight;
}
return {width:w,height:h};
}
function wndcent(){
var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0};
var _x = 0;var _y = 0;var offsetX = 0;var offsetY = 0;
//IE
if(!window.pageYOffset){
//strict mode
if(!(document.documentElement.scrollTop == 0)){offsetY = document.documentElement.scrollTop;offsetX = document.documentElement.scrollLeft;}
//quirks mode
else{offsetY = document.body.scrollTop;offsetX = document.body.scrollLeft;}}
//w3c
else{offsetX = window.pageXOffset;offsetY = window.pageYOffset;}_x = ((wndsize().width-hWnd.width)/2)+offsetX;_y = ((wndsize().height-hWnd.height)/2)+offsetY;
return{x:_x,y:_y};
}
var center = wndcent({width:350,height:350});
document.write(center.x+';<br>');
document.write(center.y+';<br>');
document.write('<DIV align="center" id="rich_ad" style="Z-INDEX: 10; left:'+center.x+'px;WIDTH: 350px; POSITION: absolute; TOP: '+center.y+'px; HEIGHT: 350px"><!--К сожалению, у Вас не установлен flash плеер.--></div>');
share|improve this answer

This is everything you need to know:

http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/

but in short:

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;
alert(x + ' × ' + y);

Fiddle

share|improve this answer
20  
Why not g = document.body ? – a paid nerd Jan 27 '14 at 3:32
26  
@apaidnerd: Standards defying browsers like IE8 do not support document.body. IE9, however, does. – Michael Mikowski Jan 27 '14 at 22:34
16  
@MichaelMikowski That is not true! Even IE5 supports document.body. – Nux Sep 27 '14 at 19:48
11  
@nux I stand corrected, and I've confirmed support in IE8. I know though that at least one brower we were targeting recently did not support document.body and we had to change to use the getElementsByTagName approach. But I guess I misremembered the browser. Sorry! – Michael Mikowski Sep 28 '14 at 1:07

A non-jQuery way to get the available screen dimension. window.screen.width/height has already been put up, but for responsive webdesign and completeness sake I think its worth to mention those attributes:

alert(window.screen.availWidth);
alert(window.screen.availHeight);

http://www.quirksmode.org/dom/w3c_cssom.html#t10 :

availWidth and availHeight - The available width and height on the screen (excluding OS taskbars and such).

share|improve this answer
    
same as width screen.height - on android chrome browser shows divided by pixel ratio :( – Darius.V Jan 30 at 9:52
    
window.screen.availHeight seems to assume full screen mode so that the normal screen mode forces scrolling (tested in Firefox and Chrome). – Suzana_K Mar 21 at 15:13

You can also get the WINDOW width and height, avoiding browser toolbars and other stuff. It is the real usable area in browser's window.

To do this, use: window.innerWidth and window.innerHeight properties (see doc at w3schools).

In most cases it will be the best way, in example, to display a perfectly centred floating modal dialog. It allows you to calculate positions on window, no matter which resolution orientation or window size is using the browser.

share|improve this answer
2  
This is not supported in ie8 nor ie7, according to w3schools. Also, you must watch out when you link to w3schools. See meta.stackexchange.com/questions/87678/… – thecarpy Feb 4 at 6:31

Here is a cross browser solution with pure JavaScript (Source):

var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
share|improve this answer
12  
This was exactly what I was looking for. I'd love to see this further on top. – Torben Feb 11 at 11:27
2  
This is better because if you are able to call the script early enough in the loading process (often the idea), then the body element will return a value of undefined as the dom isn't loaded yet. – user1167442 Aug 14 at 19:00

Sometimes you need to see the width/height changes while resizing the window and inner content.

For that I've written a little script that adds a log box that dynamicly monitors all the resizing and almost immediatly updates.

It adds a valid HTML with fixed position and high z-index, but is small enough, so you can:

  • use it on an actual site
  • use it for testing mobile/responsive views


Tested on: Chrome 40, IE11, but it is highly possible to work on other/older browsers too ... :)

  function gebID(id){ return document.getElementById(id); }
  function gebTN(tagName){ return document.getElementsByTagName(tagName); }
  function setStyleToTags(tagName, styleString){
    var tags = gebTN(tagName);
    for( var i = 0; i<tags.length; i++ ) tags[i].setAttribute('style', styleString);
  }
  function testSizes(){
    gebID( 'screen.Width' ).innerHTML = screen.width;
    gebID( 'screen.Height' ).innerHTML = screen.height;

    gebID( 'window.Width' ).innerHTML = window.innerWidth;
    gebID( 'window.Height' ).innerHTML = window.innerHeight;

    gebID( 'documentElement.Width' ).innerHTML = document.documentElement.clientWidth;
    gebID( 'documentElement.Height' ).innerHTML = document.documentElement.clientHeight;

    gebID( 'body.Width' ).innerHTML = gebTN("body")[0].clientWidth;
    gebID( 'body.Height' ).innerHTML = gebTN("body")[0].clientHeight;  
  }

  var table = document.createElement('table');
  table.innerHTML = 
       "<tr><th>SOURCE</th><th>WIDTH</th><th>x</th><th>HEIGHT</th></tr>"
      +"<tr><td>screen</td><td id='screen.Width' /><td>x</td><td id='screen.Height' /></tr>"
      +"<tr><td>window</td><td id='window.Width' /><td>x</td><td id='window.Height' /></tr>"
      +"<tr><td>document<br>.documentElement</td><td id='documentElement.Width' /><td>x</td><td id='documentElement.Height' /></tr>"
      +"<tr><td>document.body</td><td id='body.Width' /><td>x</td><td id='body.Height' /></tr>"
  ;

  gebTN("body")[0].appendChild( table );

  setStyleToTags("table",
                 "border: 2px solid black !important; position: fixed !important;"
                +"left: 50% !important; top: 0px !important; padding:10px !important;"
                +"width: 150px !important; font-size:18px; !important"
                +"white-space: pre !important; font-family: monospace !important;"
                +"z-index: 9999 !important;background: white !important;"
  );
  setStyleToTags("td", "color: black !important; border: none !important; padding: 5px !important; text-align:center !important;");
  setStyleToTags("th", "color: black !important; border: none !important; padding: 5px !important; text-align:center !important;");

  table.style.setProperty( 'margin-left', '-'+( table.clientWidth / 2 )+'px' );

  setInterval( testSizes, 200 );
share|improve this answer

If you need a truly bulletproof solution for the document width and height (the pageWidth and pageHeight in the picture), you might want to consider using a plugin of mine, jQuery.documentSize.

It has just one purpose: to always return the correct document size, even in scenarios when jQuery and other methods fail. Despite its name, you don't necessarily have to use jQuery – it is written in vanilla Javascript and works without jQuery, too.

Usage:

var w = $.documentWidth(),
    h = $.documentHeight();

for the global document. For other documents, e.g. in an embedded iframe you have access to, pass the document as a parameter:

var w = $.documentWidth( myIframe.contentDocument ),
    h = $.documentHeight( myIframe.contentDocument );

Update: now for window dimensions, too

Ever since version 1.1.0, jQuery.documentSize also handles window dimensions.

That is necessary because

  • $( window ).height() is buggy in iOS, to the point of being useless
  • $( window ).width() and $( window ).height() are unreliable on mobile because they don't handle the effects of mobile zooming.

jQuery.documentSize provides $.windowWidth() and $.windowHeight(), which solve these issues. For more, please check out the documentation.

share|improve this answer

But when we talk about responsive screens and if we want to handle it using jQuery for some reason,

window.innerWidth, window.innerHeight

gives the correct measurement. Even it removes the scroll-bar's extra space and we don't need to worry about adjusting that space :)

share|improve this answer
    
This should be the accepted answer with loads of upvotes. A much more useful answer than the currently accepted answer, and it also doesn't depend on jQuery. – developerbmw Apr 29 at 23:25
    
Unfortunately, window.innerWidth and window.innerHeight fail to take the size of the scroll bar into account. If scroll bars are present, these methods return wrong results for the window size in nearly all desktop browsers. See stackoverflow.com/a/31655549/508355 – hashchange Aug 25 at 11:13

In some cases related with responsive layout $(document).height() can return wrong data that displays view port height only. For example when some div#wrapper has height:100%, that #wrapper can be stretched by some block inside it. But it's height still will be like viewport height. In such situation you might use

$('#wrapper').get(0).scrollHeight

That represents actual size of wrapper.

share|improve this answer

You can use the Screen object to get this.

The following is an example of what it would return:

Screen {
    availWidth: 1920,
    availHeight: 1040,
    width: 1920,
    height: 1080,
    colorDepth: 24,
    pixelDepth: 24,
    top: 414,
    left: 1920,
    availTop: 414,
    availLeft: 1920
}

To get your screenWidth variable, just use screen.width, same with screenHeight, you would just use screen.height.

To get your window width and height, it would be screen.availWidth or screen.availHeight respectively.

For the pageX and pageY variables, use window.screenX or Y. Note that this is from the VERY LEFT/TOP OF YOUR LEFT/TOP-est SCREEN. So if you have two screens of width 1920 then a window 500px from the left of the right screen would have an X value of 2420 (1920+500). screen.width/height, however, display the CURRENT screen's width or height.

To get the width and height of your page, use jQuery's $(window).height() or $(window).width().

Again using jQuery, use $("html").offset().top and $("html").offset().left for your pageX and pageY values.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.