Using jQuery with CSS Media Queries

As mobile web design is becoming widely used to provide an optimal viewing experience, we as developers are need to decide the best approach with regards to device detection and choice of client or server side logic.

When using adaptive design, we can process server side logic easier using mobile device detection plugins such as 51Degrees, however a responsive/fluid site is dependent on client side detection. Since client side detection is regularly used with responsive/fluid layouts, we may find ourselves requiring some JavaScript to detect viewport sizes and media queries outside of CSS.

On a recent project, I had to process a single function in jQuery based on the browser size. Initially I was going to check the device width was applicable to a mobile device (320px):

$(window).resize(function(){

       if ($(window).width() <= 320) {  

              // is mobile device

       }     

});

 

After testing various devices and browsers, I noticed the $(window).width() and CSS media query weren’t firing together. This was due to inconsistency amongst browser windows and scrollbars. This small discrepancy causes bigger issues when accuracy is number one priority for triggering certain functions.

Solution? After trawling through StackOverflow for some hints, I found a post where a developer checked a CSS rule using jQuery that was affected within a media query condition:

 

CSS

header { width:1000px; }

@media only screen and (max-width: 320px){

       header { width:320px; }

}

 

jQuery

$(window).resize(function(){     

       if ($('header').width() == 320 ){

              // is mobile device

       }

});

 

Using this solution, regardless of how the browser treats the scrollbar, the jQuery and CSS media query will fire at exactly the same time.

Baring in mind there are various wrappers and solutions that you could use, for something so small this was more than enough.