0

given this code:

mql = window.matchMedia("(max-width: 800px)");
mql.addListener(mqlHandler);
function mqlHandler(mql) {
  if(mql.matches) {
    alert('OK');
};

and this other code:

if(Modernizr.mq("(max-width: 800px)")) {
  alert('OK');
};

the matchMedia version works as expected, it pops the alert when the size of the screen is less than 800px, no matter how many times i resize the page, however, the second one just pops an alert when i reload the page with a screen width less than 800px, if a resize the screen after that no alerts are shown.

I read this from de Modernizr docs, "A max-width or orientation query will be evaluated against the current state, which may change later." This refers to this particular behavior or there are something wrong with the code?

angvillar
  • 1,074
  • 3
  • 10
  • 25

1 Answers1

2

Modernizr.mq doesn't reevaluate on resize. It only checks when it is executed. The equivalent code would be

window.addEventListener('resize', function() {
    if(Modernizr.mq("(max-width: 800px)")) {
      alert('OK');
    };   
}, true);
Patrick
  • 13,872
  • 5
  • 35
  • 53
  • I see, Modernizr justs makes a check, your example works fine but triggers the event every time the window width changes so i think is better to use de mediaMatch approach, thx! – angvillar Feb 04 '14 at 17:08
  • Yep! you can check out respond.js if you need older browser support. – Patrick Feb 04 '14 at 18:45