Created
March 16, 2012 19:25
-
-
Save scottjehl/2051999 to your computer and use it in GitHub Desktop.
Reliably get viewport dimensions in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
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; |
Please see comments in http://stackoverflow.com/a/36132694/1722625
THANKS!
It is now 7 years after you first posted this, and this weekend I found myself needing this functionality. I have been all over Stackoverflow and a whole pile of other sites, googling like crazy. The question has been asked a zillion times and there are ten zillion answers out there - and NONE of them work. At least not in Firefox 67.0.4. None, that is, except for yours. Thank you thank you thank you!
This is FANTASTIC!!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thx a lot.
You saved a couple of my hours