Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syncing CSS and JS media queries cross-browser

When working on responsive designs I make use of CSS3 media queries, including with older browsers using respond.js. There are occasions when I also need to use JavaScript/jQuery for manipulating some elements on the page. However, when using $(window).width(), that value is often different than the value used in the CSS media query due to browser chrome and/or the presence of a vertical scrollbar, meaning a CSS media query will fire at a different breakpoint than the JS media query.

I know Modernizr alleviates this issue through the use of Modernizr.mq, but that only works in browsers that support CSS media queries to begin with, generally meaning it won't work in IE8 and below. And if you use a polyfill for adding media query support to these older browsers (e.g., respond.js), then the Modernizr.mq no longer works due to a conflict/override between the two.

What I've instead done is made use of a hidden input element on the page and given it a CSS width style within each of the media queries. I then have a function that runs automatically on the page (and on resize) that gets that width value and executes the following:

        if (width == "320px" ) {
            //Functions
        }

        //481px to 600px
        else if (width == "481px" ) {
            //Functions
        }

        //601px to 768px
        else if (width == "601px" ) {
            //Functions
        }

        //769px to 960px
        else if (width == "769px" ) {
            //Functions
        }

        //769 to 1024px
        else if (width == "961px" ) {
            //Functions
        }

        //1024px+
        else {
            //Functions
        }

This basically forces the JS to work entirely off of the CSS media query, syncing the two. This can become more specific rather than generic as I have it, instead firing based off of a specific element and a specific style that changes on that element, it depends on individual project needs.

My question then is, is there a simpler way of doing this? I've spent considerable time looking into and experimenting with this and it seems the best option thus far that takes into account older browsers as well.

like image 522
seannachie Avatar asked Nov 04 '22 00:11

seannachie


1 Answers

PPK listed a nice way to pair the CSS & JS on his blog which sort of backs up your method:

@media all and (max-width: 900px) {
// styles
}

if (document.documentElement.clientWidth < 900) {
   // scripts
}

His full post on it is here.

There's also the enquire.js plug-in.

like image 155
kaidez Avatar answered Nov 09 '22 16:11

kaidez