How to Get Screen Width and Height in JavaScript


Viewport generally refers to the space we have available in a browser window.

The viewport width and height can be found through the window and document variables.

const width = window.innerWidth 
           || document.documentElement.clientWidth
           || document.body.clientWidth;
const height = window.innerHeight
           || document.documentElement.clientHeight
           || document.body.clientHeight;

The values for width and height above will be the width and height of the usable area in the browser window.

Do note that this is a solution for targeting only modern browsers (nothing under IE8).

To target older browsers, we will have to alter how we access clientWidth.

const body = document.getElementsByTagName('body')[0];
const x = window.innerWidth 
       || document.documentElement.clientWidth
       || body.clientWidth;
const y = window.innerHeight
       || document.documentElement.clientHeight
       || body.clientHeight;