Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Accurate cross-browser viewport width
/* -----------------------------------------------
* 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
@bjankord

This comment has been minimized.

Copy link
Owner Author

@bjankord bjankord commented Jan 9, 2013

Decided to turn this gist into a full repo. Repos seem to be more discover-able than gists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment