Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need an easy way to detect CSS3 media query support using jquery

I need a quick and dirty way to detect media query support using jquery. I defined a function as follows:

function mediaQueriesEnabled () {
   var v = parseFloat($.browser.version);
   if ($.browser.msie) {
      if (v < 9)
         return (false);
   }
   return (true);
}

Can someone help me fix this up a bit? Looking at this page:

http://caniuse.com/css-mediaqueries

I realized that there are some complexities here. For example, when I test my version of safari, I get "534.57.2". I want to avoid installing modernizr for now, mainly because I'm in a crunch and I need to handle most situations in the short term. Any help is appreciated!

like image 898
Redtopia Avatar asked Dec 02 '12 01:12

Redtopia


2 Answers

EDIT: I'm no longer curating this answer as I feel that Niet's is much better (see chosen answer). It should still work, but may need some testing.

Cracking open Modernizr (which can test for media queries) we see it uses the window.matchMedia (MDN page) function. We can check in plain old vanilla JS to see if this function exists:

function mediaQueriesEnabled () {
    if(typeof window.matchMedia != "undefined" || typeof window.msMatchMedia != "undefined") {
        return true;
    } else {
        return false;
    }
}

Or more elegantly:

function mediaQueriesEnabled () {
    return (typeof window.matchMedia != "undefined" || typeof window.msMatchMedia != "undefined");
}

JSFiddle

I've tested in the following browsers that support media queries, all correctly returned true:

  • Safari Mobile
  • Chrome 26

I've tested in the following browsers that do not support media queries, all correctly returned false:

  • IE 7
like image 151
Sandy Gifford Avatar answered Nov 15 '22 06:11

Sandy Gifford


You can create a stylesheet with a media query and see if it works.

In your HTML:

<style>@media all and (min-width:1px) {
    .mediatest {position:absolute}
}</style>

(Or you could dynamically create the stylesheet, but that's harder)

Then in your script:

var d = document.createElement('div');
d.className = "mediatest";
document.body.appendChild(d);
if( window.getComputedStyle && window.getComputedStyle(d).position == "absolute") {
    // supports media queries!
}
document.body.removeChild(d);
like image 25
Niet the Dark Absol Avatar answered Nov 15 '22 07:11

Niet the Dark Absol