Created
April 16, 2012 16:35
-
-
Save bjankord/2399828 to your computer and use it in GitHub Desktop.
Accurate cross-browser viewport width
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
/* ----------------------------------------------- | |
* Accurate Cross-Browser Viewport Width | |
* https://gist.github.com/2399828 | |
* ----------------------------------------------- | |
* Copyright 2012, Brett Jankord. | |
* http://www.brettjankord.com/ | |
* | |
* Licensed under the MIT license: | |
* http://www.opensource.org/licenses/MIT | |
* ------------------------------------------------*/ | |
function viewportWidth(){ | |
var vpw; | |
var webkit = (!(window.webkitConvertPointFromNodeToPage == null)); | |
// Webkit: | |
if ( webkit ) { | |
var vpwtest = document.createElement( "div" ); | |
// Sets test div to width 100%, !important overrides any other misc. box model styles that may be set in the CSS | |
vpwtest.style.cssText = "width:100% !important; margin:0 !important; padding:0 !important; border:none !important;"; | |
document.documentElement.insertBefore( vpwtest, document.documentElement.firstChild ); | |
vpw = vpwtest.offsetWidth; | |
document.documentElement.removeChild( vpwtest ); | |
} | |
// IE 6-8: | |
else if ( window.innerWidth === undefined ) { | |
vpw = document.documentElement.clientWidth; | |
} | |
// Other: | |
else{ | |
vpw = window.innerWidth; | |
} | |
return (vpw); | |
}; | |
// Sample Usage: | |
var vpw = viewportWidth(); | |
// Notes: | |
//---------------------------------------------------------------------------------- | |
// Webkit handles media query widths differntly than most other browsers - read more below | |
// http://www.456bereastreet.com/archive/201101/media_queries_viewport_width_scrollbars_and_webkit_browsers/ | |
// Inspired by the Scott Jehl's expriemnt with getting the visible viewport dimensions | |
// https://gist.github.com/2051999 | |
// If using respond.js in IE9, the viewport width returned from the code above is no longer accurate | |
// Be sure to wrap respond.js in conditional comments so it's only used in IE8 and lower as it should be |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Decided to turn this gist into a full repo. Repos seem to be more discover-able than gists.