Skip to content Skip to sidebar Skip to footer

Make @media Max-width Behave The Same As $(window).width

While working on a website I encountered a major frustrating, yet logical problem. Take a look at this fiddle. Important CSS: * { box-sizing: border-box; -moz-box-sizing: b

Solution 1:

I think Enquire.js could fix this. It lets you bind JS functions to "media query match and unmatch events".

Using this library you could fire imgSize(); when the media query takes effect, this then eliminates the need for the $(window).width() check using jQuery inside imgSize();.

If you don't want to use a plugin, you could do it this way (copied code, untested) :

var mql = window.matchMedia("(min-width: 480px)");

mql.addListener(handleMediaChange);
handleMediaChange(mql);

var handleMediaChange = function (mediaQueryList) {
    if (mediaQueryList.matches) {
        // The browser window is at least 480px wide
    }
    else {
        // The browser window is less than 480px wide
    }
}

I think in any case its a good idea to bind your function to a media query match event instead of trying to align two different ways of getting the screen width. I'm quite sure the width of the scrollbar isn't the same across browsers, so calculating with it wouldn't be a cross-browser solution.

Post a Comment for "Make @media Max-width Behave The Same As $(window).width"