Modernizr.load shows both yep and nope alert

563 views Asked by At

I tried the following code to testing Modernizr.mq and i would like load a js code for yep.

<!doctype html>
 <html class="no-js" lang="en">
 <head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <title>S123</title>
<link rel="stylesheet" href="css/s.css" />
<script src="js/modernizr.com.js"></script>
  </head>
 <body>

<script>
  Modernizr.load({
  test: Modernizr.mq,
 yep : alert("hello, beautiful"),
 nope: alert("very poor choice of words"),
 });


  </script>

 </body>
</html>

but it gives me both, yep and nope alert.

I have no idea why, the testing code (below) works fine

if (Modernizr.mq("only screen and (min-width:480px)")) {
alert("hello");
};

Can somebody tell me what I am doing wrong?

1

There are 1 answers

1
fosfo On

from yepnopejs.com, section "What's in a test object?!" :

yepnope([{
  test : /* boolean(ish) - Something truthy that you want to test             */,
  yep  : /* array (of strings) | string - The things to load if test is true  */,
  nope : /* array (of strings) | string - The things to load if test is false */,
  both : /* array (of strings) | string - Load everytime (sugar)              */,
  load : /* array (of strings) | string - Load everytime (sugar)              */,
  callback : /* function ( testResult, key ) | object { key : fn }            */,
  complete : /* function                                                      */
}, ... ]);

so on modernizr (uses yepnope), yep expects a string or an array of strings, you can't call a function, so if you want to call a function based on whether the browser supports media queries or not, you can do:

if ( Modernizr.mq('only all') ){
    alert("hello, beautiful"); // or 
} else {
    alert("very poor choice of words");
}

from: http://modernizr.com/docs/#mq

EDIT

To run some js when the screen size is bigger than 480px, you would have to listen to the resize event on the window, then check the width of the window and then run your code, you don't need modernizr for that. For example (using jquery):

(function($){
    $(document).ready(function(){
        $( window ).resize(function() {

            var width = $( window ).width();
            if ( width > 480){

                alert("over 480"); // the js you want to run

            }

        });
    });
})(jQuery);

Don't forget to include jquery BEFORE this code. I'm sorry i can't post a link to jquery resize(), i reached link limit, i'll post a link on comments below. cheers!