Getting the Window Size in JavaScript: A Practical Guide

Learn how to reliably read the window size in JavaScript, compare viewport vs screen dimensions, and respond to resize events with debounced, cross-browser code. Includes practical examples for responsive UI and canvas sizing.

JavaScripting
JavaScripting Team
·5 min read
Quick AnswerDefinition

To get the window size in JavaScript, read the viewport dimensions with window.innerWidth and window.innerHeight. For the full-screen dimensions, use screen.width and screen.height. Detect changes by listening to the resize event on window and updating layout calculations or canvases accordingly. This approach covers most responsive UI needs. Also consider devicePixelRatio when sizing canvases or CSS pixels.

What get window size javascript means and why it matters

Understanding how to get window size javascript is essential for building responsive, high-quality web interfaces. The viewport represents the portion of the page visible to the user, typically controlled by window.innerWidth and window.innerHeight. These values change as the user resizes the browser window, rotates a device, or toggles UI chrome. By comparing viewport size to screen dimensions (screen.width and screen.height), you can make informed decisions about layout breakpoints, canvas drawing areas, and asset scaling. This knowledge also helps you optimize rendering pipelines and avoid unnecessary recalculations. In this section, you’ll see concrete code samples that demonstrate the core concepts of reading viewport and screen sizes, and you’ll learn where each metric is most appropriate for different tasks in real-world apps. get window size javascript

JavaScript
const width = window.innerWidth; const height = window.innerHeight; console.log(width, height);
JavaScript
const sw = window.screen.width; const sh = window.screen.height; console.log(sw, sh);

Why this distinction matters: viewport size governs what users can see, while screen size reflects the display hardware. For layout decisions, stick with innerWidth/innerHeight; for matching to the full display, refer to screen.width/screen.height. You’ll also encounter devicePixelRatio when calibrating canvas or image assets for crisp rendering.

tip":"Tip: Always explain which metric you’re using when presenting layout decisions, so teammates understand the basis for UI changes."],

prerequisitesSectionPlaceholder

prerequisitesSectionPlaceholder

Resize awareness: reading and reacting to size changes

responding to resize events is crucial for maintaining a smooth user experience. The basic pattern is to read the current size inside a handler and update UI components accordingly. Debouncing can reduce layout thrashing when users drag to resize. The following examples show a simple handler, and then a debounced version to align reflow with user intent. get window size javascript

JavaScript
function logSize() { console.log(`Viewport: ${window.innerWidth}x${window.innerHeight}`); } window.addEventListener('resize', logSize);
JavaScript
let resizeTimer; window.addEventListener('resize', () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(() => logSize(), 150); });

Notes on timing: debouncing ensures you don’t run expensive layout calculations on every pixel of resize. Depending on your app, you might tune the delay or switch to requestAnimationFrame for smoother visual updates. The key is to keep the UI responsive while avoiding unnecessary work.

tip":"Tip: Debounce resize handlers to reduce layout thrashing and improve perceived performance."

variationNotesSectionPlaceholder

Modern APIs: visualViewport and DPR for advanced sizing

In modern browsers, visualViewport provides layout viewport metrics that can differ from the CSS viewport when pinch-zoom or browser chrome is present. devicePixelRatio helps you scale canvases and images for crisp rendering on high-DPI displays. Feature-detect these APIs to provide fallbacks for older browsers. get window size javascript

JavaScript
if (window.visualViewport) { console.log(`Visual viewport: ${visualViewport.width}x${visualViewport.height}`); } console.log(`Device pixel ratio: ${window.devicePixelRatio}`);

If visualViewport isn’t available, rely on window.innerWidth/Height for the current layout size. Device pixel ratio becomes important when you scale canvases or render sharp graphics across DPR changes.

tip":"Tip: Use feature detection to gracefully degrade when visualViewport isn’t supported."

canvasSizingSectionPlaceholder

Practical example: responsive canvas sizing

Many visual apps rely on a canvas that matches the window size. This section demonstrates a practical approach to sizing and redrawing a canvas on resize, while keeping rendering efficient. get window size javascript

HTML
<canvas id="myCanvas"></canvas>
JavaScript
const canvas = document.getElementById('myCanvas'); function resizeCanvas() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; // redraw or re-layout content here const ctx = canvas.getContext('2d'); ctx.fillStyle = 'lightblue'; ctx.fillRect(0, 0, canvas.width, canvas.height); } let debounceTimer; window.addEventListener('resize', () => { clearTimeout(debounceTimer); debounceTimer = setTimeout(resizeCanvas, 100); }); resizeCanvas();

Walkthrough: The resizeCanvas function synchronizes the canvas dimensions with the viewport so drawings stay aligned. Debouncing ensures that redraws don’t run excessively during a resize operation. If your app uses transforms or image assets, recalculate layout and redraw on each resize as needed.

tip":"Tip: Always redraw after resizing to reflect the new canvas size."

Steps

Estimated time: 60-90 minutes

  1. 1

    Define sizing goals

    Clarify whether you need only viewport size for layout, or screen size for device matching. Decide if you’ll update canvases, images, or charts on resize.

    Tip: Align goals with UI components that actually depend on size.
  2. 2

    Read viewport size

    Implement a small function to read window.innerWidth and window.innerHeight and expose the values to your UI logic.

    Tip: Keep the function pure and side-effect free where possible.
  3. 3

    Attach resize listener

    Register a resize listener on window and call your update logic. Consider debouncing to limit frequent runs.

    Tip: Debouncing is essential for smooth resizing performance.
  4. 4

    Handle DPR and visuals

    If using canvases or high-DPI assets, incorporate window.devicePixelRatio and visualViewport when available.

    Tip: Provide a fallback for browsers that lack visualViewport.
  5. 5

    Test and refine

    Test across different browsers, devices, and orientations. Validate that the UI adapts as intended.

    Tip: Automated tests or visual regression checks help catch edge cases.
Pro Tip: Prefer viewport measurements (innerWidth/innerHeight) for responsive UI decisions.
Warning: Avoid heavy work in resize handlers; debounce or throttle to prevent jank.
Note: VisualViewport and DPR are not universal; provide fallbacks for older browsers.

Prerequisites

Required

Optional

  • A code editor or IDE for editing HTML/JS
    Optional
  • Understanding of debouncing/throttling
    Optional
  • Optional: a local server or live-reload setup
    Optional

Keyboard Shortcuts

ActionShortcut
Open DevToolsIn Chrome/Edge/Firefox to inspect, console, and elements.Ctrl++I
Toggle device toolbarPreview responsive layouts at different viewport sizes.Ctrl++M
Refresh pageReload the current page after making changes.F5 or Ctrl+R
Focus address barQuickly navigate to a URL.Ctrl+L or Alt+D

Questions & Answers

How do I get the viewport size in JavaScript?

Use window.innerWidth and window.innerHeight to read the current viewport. For full screen, check window.screen.width and window.screen.height. Pair these values with a resize listener to respond to changes.

Use innerWidth and innerHeight for the visible area, and add a resize listener to keep your UI updated.

What is the difference between innerWidth/innerHeight and screen.width/height?

innerWidth/innerHeight report the browser's layout viewport. Screen.width/height reflect the physical screen size. Use the former for responsive layouts and the latter for display-capacity considerations.

Viewport size is what users see; screen size is the display's total size.

How can I handle high-DPI canvases when resizing?

Combine window.innerWidth/Height with window.devicePixelRatio to scale the canvas correctly. Redraw content after resizing to keep visuals crisp on Retina-like displays.

Scale the canvas by devicePixelRatio and redraw after each resize.

Is visualViewport supported in all browsers?

visualViewport is supported in many modern browsers but not universally. Use feature detection and fall back to innerWidth/innerHeight when unavailable.

Check for visualViewport and use a fallback if it isn’t supported.

Should I use window.outerWidth?

Outer properties include browser chrome and are not reliable for layout decisions. Prefer innerWidth/innerHeight for UI sizing.

Don't rely on outerWidth for responsive layouts.

How can I test cross-browser window size behavior?

Test across Chrome, Edge, Firefox on desktop and mobile devices. Use emulators or device mode in DevTools to simulate various viewports.

Test across different browsers and device sizes to ensure consistent behavior.

What to Remember

  • Read viewport size with innerWidth/innerHeight
  • Monitor resize events and debounce
  • Differentiate viewport vs screen size
  • Use DPR for sharp canvases
  • Test across devices and browsers

Related Articles