How to Get the Browser Viewport Dimensions

There are two sets of properties that help you get the height and width of the viewport dimensions: innerWidth and innerHeight, and clientWidth and clientHeight.

The getWindowDims function returns an object which contains the width and height properties:

function getWindowDims() {
  let docs = document,
    win = window;
  let docsEl = (docs.compatMode && docs.compatMode === 'CSS1Compat') ?
    docs.documentElement : docs.body;
  let width = docsEl.clientWidth;
  let height = docsEl.clientHeight;
  if (win.innerWidth && width > win.innerWidth) {
    width = win.innerWidth;
    height = win.innerHeight;
  }
  return {
    width: width,
    height: height
  };
}
let win = getWindowDims();
console.log(win);

The innerWidth and innerHeight are the properties of the window object, the clientWidth and clientHeight properties are obtained for the body or documentElement property of the document object. The innerWidth and innerHeight properties contain the width and height of vertical and horizontal scrollbars. The clientWidth and clientHeight properties provide dimensions inside scrollbars. If the viewer uses a mobile device, the clientWidth and clientHeight properties would be preferable as it gives the size of the visual viewport on a mobile device.

Do you find this helpful?

Related articles