If you’re building responsive features or need to make layout decisions based on the browser size, you’ll want to know how to…
If you’re building responsive features or need to make layout decisions based on the browser size, you’ll want to know how to get the current viewport width and height using vanilla JavaScript—without relying on jQuery or any frameworks.
In this post, we’ll show you exactly how to do that with a few lines of modern, clean JavaScript.

👀 What Is the Viewport?
The viewport is the visible part of a web page in the browser window. It changes when the user resizes their window or switches devices (like going from desktop to mobile).
✅ Simple Code to Get Viewport Width & Height
Here’s the most reliable and browser-friendly way to get the current viewport dimensions:
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
console.log(`Width: ${viewportWidth}px, Height: ${viewportHeight}px`);
🎯 This will return the width and height in pixels of the browser window excluding scrollbars and dev tools.
📦 Wrap It in a Function (Reusable)
For cleaner code, you can wrap this in a function:
function getViewportSize() {
return {
width: window.innerWidth,
height: window.innerHeight
};
}
// Example usage:
const size = getViewportSize();
console.log(`Viewport is ${size.width} x ${size.height}`);
🔄 Detect When the Viewport Resizes
Want to update the size dynamically when the user resizes the window?
Just add a resize
event listener:
window.addEventListener('resize', () => {
const { width, height } = getViewportSize();
console.log(`Resized: ${width}px x ${height}px`);
});
Great for building:
- Dynamic layouts
- Responsive menus
- Element repositioning
⚠️ Older Fallback (Not Recommended Unless You Support Legacy Browsers)
If you’re supporting very old browsers (like IE8), you might see document.documentElement.clientWidth
used:
const width = document.documentElement.clientWidth || window.innerWidth;
const height = document.documentElement.clientHeight || window.innerHeight;
But in modern development, this is rarely necessary—window.innerWidth
works reliably on all current browsers.
🧪 Bonus: Log Size On Load and Resize
Here’s a full snippet to run on load and resize:
function logViewportSize() {
const width = window.innerWidth;
const height = window.innerHeight;
console.log(`Viewport size: ${width}px x ${height}px`);
}
window.addEventListener('load', logViewportSize);
window.addEventListener('resize', logViewportSize);
🎯 Final Thoughts
You don’t need a framework or plugin to get the viewport size—vanilla JavaScript handles it beautifully. Knowing how to capture width and height is essential for responsive design, lazy loading, and interactive UI elements.