Detect dynamic media queries with JavaScript without hardcoding the breakpoint widths in the script?

12,162

Solution 1

try this

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

The matches property returns true or false depending on the query result, e.g.

if (mq.matches) {

  // window width is at least 500px
} else {
  // window width is less than 500px
}

You can also add an event listener which fires when a change is detected:

// media query event handler
if (matchMedia) {
  const mq = window.matchMedia("(min-width: 500px)");
  mq.addListener(WidthChange);
  WidthChange(mq);
}

// media query change
function WidthChange(mq) {
  if (mq.matches) {
    // window width is at least 500px
  } else {
    // window width is less than 500px
  }

}

Solution 2

See this post from expert David Walsh Device State Detection with CSS Media Queries and JavaScript:

CSS

.state-indicator {
    position: absolute;
    top: -999em;
    left: -999em;
}
.state-indicator:before { content: 'desktop'; }

/* small desktop */
@media all and (max-width: 1200px) {
    .state-indicator:before { content: 'small-desktop'; }
}

/* tablet */
@media all and (max-width: 1024px) {
    .state-indicator:before { content: 'tablet'; }
}

/* mobile phone */
@media all and (max-width: 768px) {
    .state-indicator:before { content: 'mobile'; }
}

JS

var state = window.getComputedStyle(
    document.querySelector('.state-indicator'), ':before'
).getPropertyValue('content')

Also, this is a clever solution from the javascript guru Nicholas C. Zakas:

  // Test a media query.
  // Example: if (isMedia("screen and (max-width:800px)"){}
  // Copyright 2011 Nicholas C. Zakas. All rights reserved.
  // Licensed under BSD License.
  var isMedia = (function () {

    var div;

    return function (query) {

      //if the <div> doesn't exist, create it and make sure it's hidden
      if (!div) {
        div = document.createElement("div");
        div.id = "ncz1";
        div.style.cssText = "position:absolute;top:-1000px";
        document.body.insertBefore(div, document.body.firstChild);
      }

      div.innerHTML = "_<style media=\"" + query + "\"> #ncz1 { width: 1px; }</style>";
      div.removeChild(div.firstChild);
      return div.offsetWidth == 1;
    };
  })();

Solution 3

I managed to get the breakpoint values by creating width rules for invisible elements.

HTML:

<div class="secret-media-breakpoints">
    <span class="xs"></span>
    <span class="tiny"></span>
    <span class="sm"></span>
    <span class="md"></span>
    <span class="lg"></span>
    <span class="xl"></span>
</div>

CSS:

$grid-breakpoints: (
    xs:   0,
    tiny: 366px,
    sm:   576px,
    md:   768px,
    lg:   992px,
    xl:   1200px
);

.secret-media-breakpoints {
    display: none;

    @each $break, $value in $grid-breakpoints {
        .#{$break} {
            width: $value;
        }
    }
}

JavaScript:

app.breakpoints = {};
$('.secret-media-breakpoints').children().each((index, item) => {
    app.breakpoints[item.className] = $(item).css('width');
});
Share:
12,162
Timmah
Author by

Timmah

Just another web dev looking for answers while promoting open web technologies.

Updated on June 25, 2022

Comments

  • Timmah
    Timmah about 2 years

    I've been searching for a lightweight, flexible, cross-browser solution for accessing CSS Media Queries in JavaScript, without the CSS breakpoints being repeated in the JavaScript code.

    CSS-tricks posted a CSS3 animations-based solution, which seemed to nail it, however it recommends using Enquire.js instead.

    Enquire.js seems to still require the Media Query sizes to be hardcoded in the script, e.g.

    enquire.register("screen and (max-width:45em)", { // do stuff }
    

    The Problem

    All solutions so far for accessing Media Queries in Javascript seem to rely on the breakpoint being hardcoded in the script. How can a breakpoint be accessed in a way that allows it to be defined only in CSS, without relying on .on('resize')?

    Attempted solution

    I've made my own version that works in IE9+, using a hidden element that uses the :content property to add whatever I want when a Query fires (same starting point as ZeroSixThree's solution):

    HTML

    <body>
        <p>Page content</p>
        <span id="mobile-test"></span>
    </body>
    

    CSS

    #mobile-test {
        display:none;
        content: 'mq-small';
    }
    @media screen only and (min-width: 25em) {
        #mobile-test {
            content: 'mq-medium';
        }
    }
    @media screen only and (min-width: 40em) {
        #mobile-test {
            content: 'mq-large';
        }
    }
    

    JavaScript using jQuery

    // Allow resizing to be assessed only after a delay, to avoid constant firing on resize. 
    var resize;
    window.onresize = function() {
        clearTimeout(resize);
        // Call 'onResize' function after a set delay
        resize = setTimeout(detectMediaQuery, 100);
    };
    
    // Collect the value of the 'content' property as a string, stripping the quotation marks
    function detectMediaQuery() {
        return $('#mobile-test').css('content').replace(/"/g, '');
    }
    
    // Finally, use the function to detect the current media query, irrespective of it's breakpoint value
    $(window).on('resize load', function() {
        if (detectMediaQuery() === 'mq-small') {
            // Do stuff for small screens etc
        }
    });
    

    This way, the Media Query's breakpoint is handled entirely with CSS. No need to update the script if you change your breakpoints. How can this be done?