Get Device Width

05/09/2013, Thu
Categories: #JavaScript

Detect Max Screen Width

When a browser is zoomed in or resized, the reported maximum device screen width may not be what you expect. For example, you have a 1280px by 800px screen and fully maximized browser screen at 100% zoom level, but when you zoom into the page and use window.innerWidth to determine the max width, the value may not be 1280px.

To get around this limitation, matchMedia and media queries can be used to detect the max device width. Here is a something that allows you to do so:

// Get Max-Device-Width

function getDeviceWidth() {
  var isFound = false,
    commonResolutions = [
      360,
      480,
      640,
      800,
      960,
      1024,
      1280,
      1360,
      1366,
      1440,
      1600,
      1680,
      1920,
      2560,
    ];
  crLen = commonResolutions.length;
  i = 1;
  // for browsers that support matchMedia
  if (typeof window.matchMedia != "undefined") {
    i = 1;
    while (isFound === false) {
      if (window.matchMedia("(max-device-width: " + i + "px)").matches) {
        isFound = true;
        console.log("MatchMedia detects max device width as " + i + "px.");
        document.write("MatchMedia detects max device width as " + i + "px.");
      }
      i++;
    }
  } else {
    // check screen size against common resolutions
    for (var j = 0; j < crLen; j++) {
      if (
        Modernizr.mq(
          "screen and (max-device-width: " + commonResolutions[j] + "px)"
        )
      ) {
        console.log(
          "Modernizr detects max device width at " +
            commonResolutions[j] +
            "px."
        );
        document.write(
          "Modernizr detects max device width at " +
            commonResolutions[j] +
            "px."
        );
        j = crLen;
        isFound = true;
      }
    }
    // use more exhaustive approach if width is not found in common resolutions
    while (isFound === false) {
      if (Modernizr.mq("screen and (max-device-width: " + i + "px)")) {
        console.log("Modernizr detects max device width at " + i + "px.");
        document.write(
          "Modernizr detects max device width at " +
            commonResolutions[j] +
            "px."
        );
        isFound = true;
      }
      i++;
    }
  }
}

The media queries portion of the function relies on modernizr, a feature detection library, to work. You can get a custom build of modernizr to include only the media queries detection.

This function will work when the browser supports matchMedia and will fall back to using media queries if it does not. If your browser does not support either matchMedia and media queries then the function will not work. This function is tested with Opera 12.15, Chrome 26.0.1410.64, and IE 10. Firefox 20.0, however does not report the proper max-device-width when the browser window is zoomed or resized.

Demo