Viewport

Screen

Judging screen sizes and resolution with JavaScript can be difficult, not least because it can be challenging determining just what you’re measuring… and because, historically, different browsers measured different qualities of the screen using different properties.

Today, those properties are mostly standardized; it’s just a matter of learning the terms associated with each.

Viewport Width and Height

The dimensions of the active browser window:

let windowX = document.documentElement.clientWidth,
windowY = document.documentElement.clientHeight;

Measures the CSS viewport width and height when there is no scrollbar. Otherwise, equals the viewport width and height minus scrollbar width.

let windowX = window.innerWidth,
windowY = window.innerHeight;

Measures the CSS viewport width including scrollbars; can be thrown off by zoom settings on the page.

The viewport is the display area of the browser; it does not include the URL bar and browser UI.

Therefore the safest way to judge the viewport dimensions is to take the largest of these measurements:

let windowW = Math.max(document.documentElement.clientWidth, window.innerWidth),
windowH = Math.max(document.documentElement.clientHeight, window.innerHeight);

Screen Width and Height

Screen width and height are somewhat easier to calculate:

let screenW = screen.width,
screenH = screen.height;

The screen is the current display the browser is in (note that many devices can have more than one screen).

Recalculation

The one thing you have to keep in mind is that the relative “height” and “width” of a screen will change if it is rotated or resized:

  • Rotation is most common with mobile devices, but can also affect desktop screens with rotating stands.
  • Resizing affects the window width and height on desktop machines, but does not affect mobile devices.

For this reason, it’s best to declare the above variables first (making them global) and place their calculation in functions, calling the functions once on load, and again any time the appropriate event fires:

let screenW = screenH = windowW = windowH = false;

var calcScreen = function() {
  screenW = screen.width;
  screenH = screen.height;
  windowW = Math.max(document.documentElement.clientWidth, window.innerWidth);
  windowH = Math.max(document.documentElement.clientHeight, window.innerHeight);
};

calcScreen();
window.addEventListener("resize", calcScreen());
window.addEventListener("orientationchange", calcScreen());

Photograph by Luca Rossato, used under a Creative Commons license

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.
Check out the CodePen demo for this article at https://codepen.io/dudleystorey/pen/pRqyoQ