Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Media Query and Javascript/jQuery don't match up

In my CSS I have a media query like so:

@media (min-width: 800px) { /* styles */ }

And then in my jQuery, I'm targeting the window width and performing some actions.

Edit: as per the answers below, I have changed this function but my JS and CSS still didn't align. The problem was fixed by using the Modernizr function as specified in the accepted answer.

$(window).resize(function() {
    var viewportWidth = $(window).width();
    if (viewportWidth >= 800) {
        // do something
    }
});

The problem is that while the jQuery is executing bang on 800px or more, the CSS is kicking in at 740px.

Is there a known problem with these not aligning? Or could there be something on my page affecting the CSS and why it's 740px not 800px? Maybe there's something else I should be using instead of $(window)?

Edit: I've tested in Safari and it works perfectly. In Chrome and Firefox, the jQuery functions run spot on to 800px and so does the CSS. But in Chrome, the CSS actually runs after 740px, even though the media query is 800px - how can I get these to align perfectly?

like image 212
shrewdbeans Avatar asked Aug 24 '26 07:08

shrewdbeans


1 Answers

You can use Modernizr to execute the media query in JS (the mq() method will return a boolean):

$(window).resize(function() {
    if (Modernizr.mq('(min-width: 800px)')) {
        // do something
    }
});
like image 139
Jonathan Wilson Avatar answered Aug 25 '26 19:08

Jonathan Wilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!