Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reliably get viewport dimensions in JS
/*!
An experiment in getting accurate visible viewport dimensions across devices
(c) 2012 Scott Jehl.
MIT/GPLv2 Licence
*/
function viewportSize(){
var test = document.createElement( "div" );
test.style.cssText = "position: fixed;top: 0;left: 0;bottom: 0;right: 0;";
document.documentElement.insertBefore( test, document.documentElement.firstChild );
var dims = { width: test.offsetWidth, height: test.offsetHeight };
document.documentElement.removeChild( test );
return dims;
}
// Notes:
// relies on position:fixed support, but it should work in browsers that partially support position: fixed like iOS4 and such...
//sample usage: var viewportwidth = viewportSize().width;
@justin-c-rounds

This comment has been minimized.

Copy link

commented Mar 16, 2012

Curious about a couple of things:

  1. Aren't the top and left attributes overwritten by the bottom and right attributes, and therefore unnecessary?
  2. In what cases do using window.innerWidth and window.innerHeight fail to return accurate dimensions?
@scottjehl

This comment has been minimized.

Copy link
Owner Author

commented Mar 16, 2012

@justin-c-rounds

This comment has been minimized.

Copy link

commented Mar 16, 2012

Oh wicked — I've been doing something similar using a div set to display: table and 100% width/height, but this allows for pixel offsets which is nice.

Thanks for sharing!

@bjankord

This comment has been minimized.

Copy link

commented Apr 17, 2012

I've been working on a similar solution to get my javascript to fire at the same time my media queries fire on page load/resize. Webkit browsers currently render media query dimensions without the scrollbar widths, where other browsers, FF, Opera, IE9 do count scrollbar widths into the overall viewport dimensions.

matchMedia worked somewhat for what I was trying to do, but I was using respond.js for oldIE and was unable to get matchMedia.js to work on resize in oldIE so I went back to detecting the window.innerWidth to get the viewport width. I tried to fork your gist, but kept getting a 404 error when I clicked on the fork button. Anyways, here's my stab at accurately getting viewport width, I only needed the width for what I'm using it for but the concept could be expanded to get the viewport height.

Accurate viewport width:
https://gist.github.com/2399828

@Pistil-Studio

This comment has been minimized.

Copy link

commented Oct 14, 2015

thx a lot.
You saved a couple of my hours

@rabeesh

This comment has been minimized.

Copy link

commented Mar 25, 2016

@francosalcedo

This comment has been minimized.

Copy link

commented Aug 16, 2018

THANKS!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.