[javascript] 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) {
    /* ... */
}

and

@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 max-width:640px 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.

This question is related to javascript css media-queries

The answer is


Lumia phones give wrong screen.width (at least on emulator). So maybe Math.min(window.innerWidth || Infinity, screen.width) will work on all devices?

Or something crazier:

for (var i = 100; !window.matchMedia('(max-device-width: ' + i + 'px)').matches; i++) {}
var deviceWidth = i;

you can easily use

document.documentElement.clientWidth


var width = Math.max(window.screen.width, window.innerWidth);

This should handle most scenarios.


check it

const mq = window.matchMedia( "(min-width: 500px)" );

if (mq.matches) {
  // window width is at least 500px
} else {
  // window width is less than 500px
}

https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia


One issue with Bryan Rieger's useful answer is that on high-density displays, Apple devices report screen.width in dips, while Android devices report it in physical pixels. (See http://www.quirksmode.org/blog/archives/2012/07/more_about_devi.html .) I suggest using if (window.matchMedia('(max-device-width: 960px)').matches) {} on browsers supporting matchMedia.


Based on the method Bootstrap uses to set its Responsive breakpoints, the following function returns xs, sm, md, lg or xl based on the screen width:

_x000D_
_x000D_
console.log(breakpoint());

function breakpoint() {
    let breakpoints = {
        '(min-width: 1200px)': 'xl',
        '(min-width: 992px) and (max-width: 1199.98px)': 'lg',
        '(min-width: 768px) and (max-width: 991.98px)': 'md',
        '(min-width: 576px) and (max-width: 767.98px)': 'sm',
        '(max-width: 575.98px)': 'xs',
    }

    for (let media in breakpoints) {
        if (window.matchMedia(media).matches) {
            return breakpoints[media];
        }
    }

    return null;
}
_x000D_
_x000D_
_x000D_


You should use

document.documentElement.clientWidth

It is regarded as cross-browser compability, and is the same method that jQuery(window).width(); uses.

For detailed information have a look at: https://ryanve.com/lab/dimensions/


I just had this idea, so maybe it's shortsighted, but it seems to work well and might be the most consistent between your CSS and JS.

In your CSS you set the max-width value for html based on the @media screen value:

@media screen and (max-width: 480px) and (orientation: portrait){

    html { 
        max-width: 480px;
    }

    ... more styles for max-width 480px screens go here

}

Then, using JS (probably via a framework like JQuery), you would just check the max-width value of the html tag:

maxwidth = $('html').css('max-width');

Now you can use this value to make conditional changes:

If (maxwidth == '480px') { do something }

If putting the max-width value on the html tag seems scary, then maybe you can put on a different tag, one that is only used for this purpose. For my purpose the html tag works fine and doesn't affect my markup.


Useful if you are using Sass, etc: To return a more abstract value, such as breakpoint name, instead of px value you can do something like:

  1. Create an element that will store the breakpoint name, e.g. <div id="breakpoint-indicator" />
  2. Using css media queries change the content property for this element, e. g. "large" or "mobile", etc (same basic media query approach as above, but setting css 'content' property instead of 'max-width').
  3. Get the css content property value using js or jquery (jquery e.g. $('#breakpoint-indicator').css('content');), which returns "large", or "mobile", etc depending on what the content property is set to by the media query.
  4. Act on the current value.

Now you can act on same breakpoint names as you do in sass, e.g. sass: @include respond-to(xs), and js if ($breakpoint = "xs) {}.

What I especially like about this is that I can define my breakpoint names all in css and in one place (likely a variables scss document) and my js can act on them independently.


Just as an FYI, there is a library called breakpoints which detects the max-width as set in CSS and allows you to use it in JS if-else conditions using <=, <, >, >= and == signs. I found it quite useful. The payload size is under 3 KB.


Ya mybe u can use document.documentElement.clientWidth to get the device width of client and keep tracking the device width by put on setInterval

just like

setInterval(function(){
        width = document.documentElement.clientWidth;
        console.log(width);
    }, 1000);

I think using window.devicePixelRatio is more elegant than the window.matchMedia solution:

if (window.innerWidth*window.devicePixelRatio <= 960 
    && window.innerHeight*window.devicePixelRatio <= 640) { 
    ... 
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to media-queries

iPhone X / 8 / 8 Plus CSS media queries What is correct media query for IPad Pro? How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript? CSS media query to target only iOS devices How to set portrait and landscape media queries in css? iPhone 6 and 6 Plus Media Queries Responsive design with media query : screen size? Bootstrap 3 breakpoints and media queries $(window).width() not the same as media query How to make responsive table