Device and Viewport Size In JavaScript

viewport

How to get the viewport size: jQuery's $(window).width() is highly regarded as cross-browser compatible. JavaScript's document.documentElement.clientWidth is faster and is cross-browser compatible. Look in the jQuery source: they use document.documentElement.clientWidth. The tables below compare these live against the less consistent inner/outer methods. Update: correctedViewportW is a custom function that further normalizes browser difference, and is now the technique used in verge and Response.

width methodslive output
$(window).width() undefined
document.documentElement.clientWidthundefined
window.innerWidthundefined
window.outerWidthundefined
@media breakpoint
correctedViewportW()
height methodslive output
$(window).height() undefined
document.documentElement.clientHeightundefined
window.innerHeightundefined
window.outerHeightundefined
@media breakpoint
correctedViewportH()

device

How to get the device size: It's simple. Use window.screen.width for device width and window.screen.height for device height. The .availWidth/.availHeight methods give you the device size minus UI taskbars (try on an iPhone) and are slower outside of Webkit. Device size is static and does not change when the page is resized or rotated.

width methodslive output
window.screen.widthundefined
window.screen.availWidthundefined
@media breakpoint
height methodslive output
window.screen.heightundefined
window.screen.availHeightundefined
@media breakpoint

document

For further comparison, here are document size methods (not usually needed for responsive design but useful in other regards such as scrolling apps). Note the difference between $(document).width() and some of the others (especially when the window is wider than the max-width of the body). jQuery uses the Math.max of 5 numbers to calculate this: the last 4 in these blocks and the docElem's clientWidth / clientHeight. For decent cross-browser support I think the Math.max of the last 3 in these blocks is sufficient rather than the 5 jQuery uses.

width methodslive output
$(document).width()undefined
document.body.clientWidthundefined
document.body.offsetWidthundefined
document.body.scrollWidthundefined
document.documentElement.clientWidthundefined
document.documentElement.offsetWidthundefined
document.documentElement.scrollWidthundefined
height methodslive output
$(document).height() undefined
document.body.clientHeightundefined
document.body.offsetHeightundefined
document.body.scrollHeightundefined
document.documentElement.clientHeightundefined
document.documentElement.offsetHeightundefined
document.documentElement.scrollHeightundefined