JavaScript to Determine Viewport Size

JavaScript provided on this page allows you to determine the size of the user's browser window, aka the viewport dimensions.

Two sets of properties are available for obtaining the width and height of the browser window: innerWidth and innerHeight[1], or clientWidth and clientHeight. While innerWidth and innerHeight are properties of the window object, clientWidth and clientHeight are obtained for either the body or documentElement property of the document object, depending upon whether the document is in standards or quirks mode.

The innerWidth and innerHeight properties include the width and height of vertical and horizontal scrollbars if they are present. The clientWidth and clientHeight properties give dimensions inside of scrollbars. So to get the best measure of the available space in the browser window, clientWidth and clientHeight are preferable.

Function to Determine Viewport Size

The function displayed below determines the available space within the browser window. Results for the current window are displayed to the right. Resize your browser window and these values will be recalculated.

function dw_getWindowDims() {
    var doc = document, w = window;
    var docEl = (doc.compatMode && doc.compatMode === 'CSS1Compat')?
            doc.documentElement: doc.body;
    var width = docEl.clientWidth;
    var height = docEl.clientHeight;
    // mobile zoomed in?
    if ( w.innerWidth && width > w.innerWidth ) {
        width = w.innerWidth;
        height = w.innerHeight;
    return {width: width, height: height};

Function Explanation and Usage

The dw_getWindowDims function returns an object containing width and height properties. The document.compatMode property is used to determine whether the document is in standards or quirks mode. Then clientWidth and clientHeight are obtained for the appropriate element (body or documentElement).

Generally innerWidth and innerHeight would be greater than or equal to clientWidth and clientHeight since they include the size of scrollbars if present. However, if the viewer is on a mobile device and zoomed in, clientWidth and clientHeight would be greater, so innerWidth and innerHeight are used in that case. This gives us the size of the visual viewport on a mobile device.[2]

// example usage
var dims = dw_getWindowDims();
alert( dims.width );

Viewport dimensions are used to display Tooltips within the available window space.

  1. Internet Explorer prior to version nine does not support innerWidth and innerHeight properties. ^
  2. See PPK's discussion of the two viewports on mobile devices. ^