How can I get windowWidth
, windowHeight
, pageWidth
, pageHeight
, screenWidth
, screenHeight
,
I am surprised that question have about 10 years and it looks like so far nobody has given a full answer (with 10 values) yet. So I carefully analyse OP question (especially picture) and have some remarks
(0,0)
is in the viewport (browser window without bars and main borders) top left corner and axes are directed to right and down (what was marked on OP picture) so the values of pageX, pageY, screenX, screenY
must be negative (or zero if page is small or not scrolled)screenHeight/Width
OP wants to count screen height/width including system menu bar (eg. in MacOs) - this is why we NOT use .availWidth/Height
(which not count it)windowWidth/Height
OP don't want to count size of scroll bars so we use .clientWidth/Height
screenY
- in below solution we add to position of top left browser corner (window.screenY
) the height of its menu/tabls/url bar). But it is difficult to calculate that value if download-bottom bar appears in browser and/or if developer console is open on page bottom - in that case this value will be increased of size of that bar/console height in below solution. Probably it is impossible to read value of bar/console height to make correction (without some trick like asking user to close that bar/console before measurements...)pageWidth
- in case when pageWidth is smaller than windowWidth we need to manually calculate size of
children elements to get this value (we do example calculation in contentWidth
in below solution - but in general this can be difficult for that case)
margin=0 - if not then you should consider this values when calculate pageWidth/Height
and pageX/Y
function sizes() {
let contentWidth = [...document.body.children].reduce(
(a, el) => Math.max(a, el.getBoundingClientRect().right), 0)
- document.body.getBoundingClientRect().x;
return {
windowWidth: document.documentElement.clientWidth,
windowHeight: document.documentElement.clientHeight,
pageWidth: Math.min(document.body.scrollWidth, contentWidth),
pageHeight: document.body.scrollHeight,
screenWidth: window.screen.width,
screenHeight: window.screen.height,
pageX: document.body.getBoundingClientRect().x,
pageY: document.body.getBoundingClientRect().y,
screenX: -window.screenX,
screenY: -window.screenY - (window.outerHeight-window.innerHeight),
}
}
// TEST
function show() {
console.log(sizes());
}
body { margin: 0 }
.box { width: 3000px; height: 4000px; background: red; }
CAUTION: stackoverflow snippet gives wrong values for screenX-Y,
but if you copy its code to your page directly the values will be right
I test it on Chrome 83.0, Safari 13.1, Firefox 77.0 and Edge 83.0