Skip to main content Accessibility Feedback

The Viewport

Unless otherwise noted, these work in all modern browsers, and IE9+. You can extend support back further with polyfills.

Get the viewport height

There are two methods to get the viewport height: window.innerHeight and document.documentElement.clientHeight. The former is more accurate. The latter has better browser support.

To get the best of both worlds, try innerHeight first, and fallback to clientHeight if not supported.

var viewportHeight = window.innerHeight || document.documentElement.clientHeight;

Get the viewport width

There are two methods to get the viewport width: window.innerWidth and document.documentElement.clientWidth. The former is more accurate. The latter has better browser support.

To get the best of both worlds, try innerWidth first, and fallback to clientWidth if not supported.

var viewportWidth = window.innerWidth || document.documentElement.clientWidth;

Check if an element is in the viewport

isInViewport() is a helper method I wrote to check if any part of an element is in the viewport. It returns true if any part of the element is in the viewport, and false if it’s not.

var elem = document.querySelector('#some-element');
isInViewport(elem); // Boolean: returns true/false