Search code examples
javascriptjquerycsssassmedia-queries

jQuery: Check if window is smaller than x units other than pixels (e.g. em, rem)?


Sounds trivial but how can I actually check this? I have the following breakpoints in SASS:

$width_breakpoints: (
        small: 39.9375em,
        medium: 40em,
        large: 76em
);

Now I want to check the following (Pseudo-Code):

if($(window).width() < 39.9375em) {
    // add current-mode-mobile class to a certain element
}

How can I actually check if the width is smaller than X em or X rem or X percent?


Solution

  • For IE10+:

    if (window.matchMedia("(min-width: 39.9375em)").matches) {
      /* the viewport is at least 39.9375 em wide */
    } else {
      /* the viewport is less than 39.9375 em wide */
    }