Modernizr media query not working?

Tag: modernizr Author: liubingqian Date: 2011-10-06

I included Modernizr on my site:

<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/modernizr.custom.js"></script>

and I have this in custom.js:

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

I resized my browser to be 480px, refreshed the site, but I didn't see any alert.

Any suggestions to fix this?

Best Answer

You need the unit value px in your media query:

Your line:

if (Modernizr.mq("screen and (max-width:480)")) {\

Should be:

if (Modernizr.mq("screen and (max-width:480px)")) {

comments:

Thank that was a typo.

Other Answer1

Wesley is right, but just a quick note to remember is if (Modernizr.mq("screen and (max-width:480px)")) { will still only trigger if the media query conditions are met!

So if you're screen is larger than 480px and this script is called, it won't alert.

Created this just today to trigger a script when a media query is trigger (with IE fallback):

            //Test to see if media queries are acceptable
            if(Modernizr.mq('only all')){
                var mql = window.matchMedia('(max-width: 980px)');

                mql.addListener(tabletChange);
                tabletChange(mql);

                function tabletChange(mediaQueryList) {
                    //If media query triggered 
                    if (mediaQueryList.matches) {      
                        //SMALL SCREEN
                    } else {
                        //LARGE SCREEN
                    }
                }

            } else {

                var resizeTimer;
                mediaMatchFallback();

                $(window).resize(function(){
                    if(resizeTimer){
                        clearTimeout(resizeTimer);
                    }
                    resizeTimer = setTimeout(mediaMatchFallback, 500);
                });

                function mediaMatchFallback(){
                    if($(window).width() <= 980){
                        //SMALL SCREEN
                    }else{
                        //LARGE SCREEN
                    }
                }
            }