How to get the browser viewport dimensions?

Alix Axel picture Alix Axel · Aug 8, 2009 · Viewed 671.2k times · Source

I want to provide my visitors the ability to see images in high quality, is there any way I can detect the window size?

Or better yet, the viewport size of the browser with JavaScript? See green area here:

Answer

ryanve picture ryanve · Jan 16, 2012

Cross-browser @media (width) and @media (height) values 

const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0)
const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)

window.innerWidth and window.innerHeight

  • gets CSS viewport @media (width) and @media (height) which include scrollbars
  • initial-scale and zoom variations may cause mobile values to wrongly scale down to what PPK calls the visual viewport and be smaller than the @media values
  • zoom may cause values to be 1px off due to native rounding
  • undefined in IE8-

document.documentElement.clientWidth and .clientHeight


Resources