Nicholas Evans Nicholas Evans - 9 months ago 57
CSS Question

Get the device width in javascript

Is there a way to get the users device width, as opposed to viewport width, using javascript?

CSS media queries offer this, as I can say

@media screen and (max-width:640px) {
/* ... */


@media screen and (max-device-width:960px) {
/* ... */

This is useful if I'm targeting smartphones in landscape orientation. For example, on iOS a declaration of
will target both landscape and portrait modes, even on an iPhone 4. This is not the case for Android, as far as I can tell, so using device-width in this instance successfully targets both orientations, without targeting desktop devices.

However, if I'm invoking a javascript binding based on device width, I appear to be limited to testing the viewport width, which means an extra test as in the following,

if ($(window).width() <= 960 && $(window).height <= 640) { /* ... */ }

This doesn't seem elegant to me, given the hint that device width is available to css.

Answer Source

You can get the device screen width via the screen.width property.
Sometimes it's also useful to use window.innerWidth (not typically found on mobile devices) instead of screen width when dealing with desktop browsers where the window size is often less than the device screen size.

Typically, when dealing with mobile devices AND desktop browsers I use the following:

 var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;