Getting Browser Window Size with JavaScript

Use-Cases of this Tutorial

  • You are looking to get the dimensions of the visible part of the browser.
  • You are looking to get dimensions of the entire browser window.
  • You are looking to detect a dynamic change in window size.

JavaScript has built-in methods which returns the browser window dimensions. We can also listen to an event to track resizing of the browser window.

Demo

See the live dimensions for the current window below :

Height and Width of the Viewport Window

The viewport is the section of the browser window where webpages are rendered. It does not include the location bar, menu bar, or other toolbars of the browser.

  • Dimensions including scrollbars : Viewport dimensions can be obtained from the window.innerWidth and window.innerHeight properties. These properties include dimensions of the vertical / horizontal scrollbars also (if present).

    var viewport_width = window.innerWidth;
    var viewport_height = window.innerHeight;
    
  • Dimensions excluding scrollbars : The viewport dimensions, excluding scrollbar dimensions can be obtained through document.documentElement.clientWidth and document.documentElement.clientHeight properties. These properties refer to the size of the visible HTML document.

    // viewport width without vertical scrollbar
    var viewport_width = document.documentElement.clientWidth;
    
    // viewport height without horizontal scrollbar
    var viewport_height = document.documentElement.clientHeight;
    

Width and Height of the Full Browser Window

The dimensions of the full browser window can be obtained from the window.outerWidth and window.outerHeight properties. This include the dimensions of everything — location bar, menu bar, scrollbars, other toolbars etc.

var full_window_width = window.outerWidth;
var full_window_height = window.outerHeight;

Detecting Change in Window Size

To detect change in window size we can listen to resize event on the window object.

// will be called whenever window size changes
window.addEventListener('resize', function() {
	// viewport and full window dimensions will change
	
	var viewport_width = window.innerWidth;
	var viewport_height = window.innerHeight;
});