Get the device width in javascript

JavascriptCssMedia Queries

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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;

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Solution 4 - Javascript

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

This should handle most scenarios.

Solution 5 - Javascript

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/

Solution 6 - Javascript

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

Solution 7 - Javascript

You can easily use

document.documentElement.clientWidth

Update

For example:

let el = document.getElementById('result');
el.innerText = document.documentElement.clientWidth;
window.addEventListener('resize', function(event) {
    // do what you want
    el.innerText = document.documentElement.clientWidth;
}, true);

<!DOCTYPE html>
  <html>
     <body>
      <div id="result"></div>
     </body>
  </html>

Solution 8 - Javascript

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

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

Solution 9 - Javascript

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;

Solution 10 - Javascript

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:

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;
}

Solution 11 - Javascript

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);

Solution 12 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNicholas EvansView Question on Stackoverflow
Solution 1 - JavascriptBryan RiegerView Answer on Stackoverflow
Solution 2 - Javascriptuser69173View Answer on Stackoverflow
Solution 3 - JavascriptRogerRogerView Answer on Stackoverflow
Solution 4 - JavascriptZNSView Answer on Stackoverflow
Solution 5 - JavascriptFooBarView Answer on Stackoverflow
Solution 6 - JavascriptMEAbidView Answer on Stackoverflow
Solution 7 - JavascriptReundoView Answer on Stackoverflow
Solution 8 - Javascriptmaxime schoeniView Answer on Stackoverflow
Solution 9 - JavascriptMunawwarView Answer on Stackoverflow
Solution 10 - JavascriptOmid AriyanView Answer on Stackoverflow
Solution 11 - JavascriptJ. PatView Answer on Stackoverflow
Solution 12 - JavascriptAbhishek DivekarView Answer on Stackoverflow