Question
Get Screen, Page, and Browser Window Size in JavaScript
Question
How can I get the following measurements in JavaScript so they work reliably across all major browsers?
windowWidthwindowHeightpageWidthpageHeightscreenWidthscreenHeightpageXpageYscreenXscreenY
I want a cross-browser way to read:
- the browser viewport size
- the full page/document size
- the physical screen size
- the current page scroll position
- the browser window position on the screen
Short Answer
By the end of this page, you will understand the difference between screen size, browser viewport size, document size, scroll position, and browser window position in JavaScript. You will also learn a practical cross-browser pattern for reading these values safely in real projects.
Concept
In browser JavaScript, several different measurements describe the visible environment of a web page. These values sound similar, but they refer to different things.
The main measurements
Viewport size
The viewport is the visible area inside the browser where the page is rendered.
windowWidthusually means the viewport widthwindowHeightusually means the viewport height
These are commonly read from:
window.innerWidth
window.innerHeight
Older browsers may instead require values from document.documentElement or document.body.
Document or page size
The page size is the full size of the document, including content not currently visible because you need to scroll.
pageWidthpageHeight
These are usually calculated from document properties such as:
scrollWidthscrollHeightoffsetWidthoffsetHeightclientWidthclientHeight
Screen size
The screen refers to the user's physical display, not the browser tab.
screenWidthscreenHeight
These come from:
screen.width
screen.height
Scroll position
The page scroll position tells you how far the document has been scrolled.
pageXis horizontal scroll offsetpageYis vertical scroll offset
These are often read from:
window.pageXOffset
window.pageYOffset
Older browser fallbacks may use document.documentElement.scrollLeft and similar properties.
Browser window position on the screen
The browser window position tells you where the browser window is located on the user's screen.
screenXscreenY
These are often read from:
window.screenX
window.screenY
Some browsers historically used screenLeft and screenTop.
Why this matters
In real programming, these values are useful for:
- responsive layouts
- positioning popups or overlays
- lazy loading and scroll-based effects
- analytics and UI behavior
- drag/drop or multi-window tools
The key idea is that viewport, document, screen, and scroll are not the same thing. Many bugs happen because developers mix them up.
Mental Model
Think of a website like a large poster hanging on a wall.
- The screen is the whole wall.
- The browser window is the picture frame placed on the wall.
- The viewport is the glass opening inside that frame where you can see the poster.
- The page/document is the full poster, even the parts hidden outside the frame.
- The scroll position is how far you have slid the poster behind the frame.
- The window position on screen is where the frame sits on the wall.
This analogy helps you remember why these measurements are different even though they all describe size or position.
Syntax and Examples
Cross-browser helper
A common approach is to build one helper object that collects all the measurements you need.
function getBrowserMetrics() {
const doc = document.documentElement;
const body = document.body;
const windowWidth = window.innerWidth || doc.clientWidth || body.clientWidth;
const windowHeight = window.innerHeight || doc.clientHeight || body.clientHeight;
const pageWidth = Math.max(
body.scrollWidth,
doc.scrollWidth,
body.offsetWidth,
doc.offsetWidth,
body.clientWidth,
doc.clientWidth
);
const pageHeight = Math.max(
body.scrollHeight,
doc.scrollHeight,
body.offsetHeight,
doc.offsetHeight,
body.clientHeight,
doc.clientHeight
);
const screenWidth = window.screen.width;
const screenHeight = window.screen.height;
const pageX = window.pageXOffset || doc.scrollLeft || body.scrollLeft || 0;
const pageY = window.pageYOffset || doc.scrollTop || body.scrollTop || 0;
const screenX = window.screenX !== undefined ? window.screenX : window.screenLeft;
const screenY = window.screenY !== undefined ? window.screenY : window.screenTop;
return {
windowWidth,
windowHeight,
pageWidth,
pageHeight,
screenWidth,
screenHeight,
pageX,
pageY,
screenX,
screenY
};
}
console.log(getBrowserMetrics());
What this does
- Uses
window.innerWidthandwindow.innerHeightfirst for viewport size - Falls back to
document.documentElementanddocument.bodyfor older browser behavior - Uses
Math.max(...)to get the full document size reliably - Reads screen dimensions from
window.screen - Reads scroll position from
pageXOffsetandpageYOffsetwith fallbacks - Reads browser window position using
screenX/screenYor olderscreenLeft/screenTop
Simple example in a page
const metrics = getBrowserMetrics();
console.log("Viewport:", metrics.windowWidth, metrics.windowHeight);
console.log("Page:", metrics.pageWidth, metrics.pageHeight);
console.log("Screen:", metrics.screenWidth, metrics.screenHeight);
console.log("Scroll:", metrics.pageX, metrics.pageY);
console.log("Window position:", metrics.screenX, metrics.screenY);
This is a beginner-friendly pattern because it keeps all related values in one place.
Step by Step Execution
Example
function getScrollY() {
return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
}
const y = getScrollY();
console.log(y);
Step by step
1. Call getScrollY()
JavaScript starts evaluating the return expression.
2. Check window.pageYOffset
If the browser supports window.pageYOffset and it has a usable value, that value is returned immediately.
Example:
window.pageYOffset === 300
Then getScrollY() returns 300.
3. Fallback to document.documentElement.scrollTop
If window.pageYOffset is unavailable or falsy, JavaScript checks:
document.documentElement.scrollTop
This is often the scroll value for the root HTML element.
4. Fallback to document.body.scrollTop
If that also does not work, JavaScript tries:
document.body.scrollTop
This was needed in some older browser behaviors.
5. Use 0 as a safe default
If none of the previous values work, the function returns 0.
Why this pattern is useful
This is called a fallback chain. It is common in browser code where the same information may be exposed through slightly different properties depending on browser behavior.
Real World Use Cases
Responsive interfaces
Apps often need the viewport size to decide how components should render.
Examples:
- showing a mobile menu below a certain width
- resizing a canvas or chart
- adjusting modal or sidebar layout
Infinite scroll and lazy loading
Scroll position and page height are used to detect when the user is near the bottom of the page.
const metrics = getBrowserMetrics();
const nearBottom = metrics.pageY + metrics.windowHeight > metrics.pageHeight - 200;
Analytics and behavior tracking
A team may want to know:
- how large users' screens are
- how much users scroll
- whether content is seen above the fold
Popup or multi-window tools
Screen position is useful when opening helper windows or keeping a popup aligned relative to the current browser window.
Large document viewers
Editors, dashboards, and documentation sites may compare viewport size and page size to decide:
- whether scrollbars are needed
- how much content is visible
- when to stick headers or navigation
Real Codebase Usage
In real projects, developers rarely read these values inline everywhere. Instead, they usually wrap them in utility functions or hooks.
Common patterns
Utility function
A shared helper avoids repeating browser-specific fallbacks.
function getViewportSize() {
const doc = document.documentElement;
const body = document.body;
return {
width: window.innerWidth || doc.clientWidth || body.clientWidth,
height: window.innerHeight || doc.clientHeight || body.clientHeight
};
}
Guard clauses
In some environments, window does not exist, such as server-side rendering.
function getSafeScreenWidth() {
if (typeof window === "undefined") {
return 0;
}
return window.screen.width;
}
Event-driven updates
Real apps often recompute values on resize and scroll.
window.addEventListener("resize", () => {
console.log(getBrowserMetrics());
});
window.addEventListener("scroll", () => {
console.log(getBrowserMetrics());
});
Early return for unsupported values
If window position is not available or meaningful in a browser context, developers may return null instead of guessing.
function getWindowScreenPosition() {
if (typeof window === "undefined") {
return null;
}
return {
x: window.screenX !== undefined ? window.screenX : window.screenLeft,
y: window.screenY !== undefined ? window.screenY : window.screenTop
};
}
Validation before layout logic
Developers often check values before using them in calculations.
const { windowHeight, pageHeight } = getBrowserMetrics();
if (pageHeight <= windowHeight) {
console.log("No vertical scrolling needed");
}
Common Mistakes
Mixing up viewport size and page size
A very common mistake is assuming window.innerHeight is the full document height.
Broken code
const fullHeight = window.innerHeight;
This only gives the visible viewport height, not the full page height.
Better
const fullHeight = Math.max(
document.body.scrollHeight,
document.documentElement.scrollHeight
);
Using only one property with no fallback
Fragile code
const scrollY = document.body.scrollTop;
This may not work consistently across browser modes.
Better
const scrollY = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
Confusing screen position with page scroll
screenXandscreenYare the browser window's position on the physical screenpageXandpageYusually refer to document scroll offsets in this context
These values are not interchangeable.
Forgetting that screen.width is not the browser width
Incorrect assumption
if (screen.width < 768) {
// must be a small browser window
}
This checks the device screen size, not the current browser viewport size.
Better
if (window.innerWidth < 768) {
// viewport is small
}
Ignoring standards mode differences
Some document measurements differ depending on rendering mode. Using both document.documentElement and document.body as fallbacks is a safer pattern for older cross-browser code.
Forgetting server-side rendering
If your code runs in Node.js or during server rendering, browser globals may not exist.
if (typeof window !== "undefined") {
console.log(window.innerWidth);
}
Comparisons
Similar browser measurement concepts
| Concept | What it means | Common property | Important note |
|---|---|---|---|
| Viewport width/height | Visible page area inside browser | window.innerWidth, window.innerHeight | Changes when browser is resized |
| Page width/height | Full document size | scrollWidth, scrollHeight | Includes off-screen content |
| Screen width/height | Physical display size | screen.width, screen.height | Not the same as viewport |
| Scroll position | How far page is scrolled | pageXOffset, pageYOffset | Changes while user scrolls |
| Window screen position | Browser window location on monitor | screenX, screenY | Refers to browser window, not document |
innerWidth vs clientWidth
| Property | Meaning | Typical use |
|---|---|---|
window.innerWidth | Viewport width including scrollbar area behavior defined by browser | Preferred first choice for viewport size |
document.documentElement.clientWidth | Width of root element's visible content area | Good fallback for older browser patterns |
document.body.clientWidth | Body visible width | Older fallback |
pageYOffset vs scrollTop
| Property | Where it lives | Notes |
|---|---|---|
window.pageYOffset | window | Clean modern choice for scroll offset |
document.documentElement.scrollTop | root element | Useful fallback |
document.body.scrollTop | body element | Older fallback in some browsers |
Cheat Sheet
Quick reference
const viewportWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
const viewportHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
const pageWidth = Math.max(
document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.body.clientWidth,
document.documentElement.clientWidth
);
const pageHeight = Math.max(
document.body.scrollHeight,
document.documentElement.scrollHeight,
document.body.offsetHeight,
document.documentElement.offsetHeight,
document.body.clientHeight,
document.documentElement.clientHeight
);
const screenWidth = window.screen.width;
const screenHeight = window.screen.height;
const pageX = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
const pageY = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
const screenX = window.screenX !== undefined ? window.screenX : window.screenLeft;
const screenY = window.screenY !== undefined ? window.screenY : window.screenTop;
Remember
- Viewport = visible part of the page
- Page = full document size
- Screen = monitor/display size
- pageX/pageY = scroll offsets
- screenX/screenY = browser window location on monitor
Safe pattern
- Prefer modern property first
- Add fallbacks for older browser behavior
- Return
0ornullwhen appropriate - Wrap logic in a helper function for reuse
FAQ
How do I get the browser window size in JavaScript?
Use viewport measurements such as window.innerWidth and window.innerHeight, with fallbacks to document.documentElement.clientWidth and clientHeight for older behavior.
What is the difference between page size and window size?
Window size is the visible viewport. Page size is the full document, including content outside the visible area that requires scrolling.
How do I get the scroll position of a page?
Use window.pageXOffset and window.pageYOffset, with fallbacks to document.documentElement.scrollLeft, scrollTop, and document.body values.
Is screen.width the same as browser width?
No. screen.width is the width of the user's physical display. Browser width is the viewport width, usually window.innerWidth.
How do I get the browser window position on the screen?
Use window.screenX and window.screenY. Older browser code may use window.screenLeft and window.screenTop as fallbacks.
Why do I need fallbacks for browser measurements?
Different browsers and older browser modes exposed these values through different properties. Fallbacks make your code more reliable.
Should I still use cross-browser measurement helpers today?
Yes, especially if you want one reusable function for viewport, page, scroll, and screen values in a consistent format.
Mini Project
Description
Build a small browser metrics panel that displays the current viewport size, full page size, screen size, scroll position, and browser window position. This project is useful because it turns abstract browser measurements into something visible and easy to test while resizing and scrolling the page.
Goal
Create a page that reads browser measurement values and updates them when the user scrolls or resizes the window.
Requirements
- Create a function that returns viewport, page, screen, scroll, and window position values.
- Show all measurement values on the page.
- Update the displayed values when the page loads, when the user scrolls, and when the window resizes.
- Use cross-browser fallbacks for viewport and scroll values.
Keep learning
Related questions
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.