wyc
wyc

Reputation: 55283

Modernizr media query not working?

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?

Upvotes: 1

Views: 6864

Answers (2)

Chris GW Green
Chris GW Green

Reputation: 1199

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
                    }
                }
            }

Upvotes: 1

No Results Found
No Results Found

Reputation: 102745

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)")) {

Upvotes: 5

Related Questions