Getting Browser Window Size with JavaScript

Use-Cases of this Tutorial

  • Get dimensions of the entire browser window.
  • Get dimensions of section of the browser where pages are displayed.
  • Detect a change in window size.

window.innerWidth & window.innerHeight gives the width & height of the viewport window. 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.

window.outerWidth & window.outerHeight gives the width & height of the full browser window that includes the location bar, menu etc.

See also  Infinite Grid System Based On CSS Flexbox - Flex One

Width of the Viewport Window

  • window.innerWidth gives the width of viewport window including the width of the vertical scrollbar also.
    var viewport_width = window.innerWidth;
  • document.documentElement.clientWidth gets the viewport width excluding scrollbar.
    // viewport width without vertical scrollbar
    var viewport_width = document.documentElement.clientWidth;

Height of the Viewport Window

  • window.innerHeight gives the height of viewport window including the height of the horizontal scrollbar also.
    var viewport_height = window.innerHeight;
  • document.documentElement.clientHeight gets the viewport height excluding scrollbar.
    // viewport height without horizontal scrollbar
    var viewport_height = document.documentElement.clientHeight;

Width of the Full Browser Window

window.outerWidth gives the width of the full window including location bar, menu bar, scrollbars, other toolbars etc.

var full_window_width = window.outerWidth;

Height of the Full Browser Window

window.outerHeight gives the height of the full window that includes location bar, menu etc.

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;

Live Example

See the live dimensions for the current window below :

Leave a Reply

Your email address will not be published. Required fields are marked *