2

How can I detect via JavaScript if browser supports CSS3 media queries?

How can I detect via JavaScript if browser supports CSS3 gradient?

Thank you.

weilou
  • 4,419
  • 10
  • 43
  • 56

1 Answers1

14

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 (Modernizr is really awesome, but sometimes you just want a brick, not a house):

function mediaQueriesSupported()
{
    if(typeof window.matchMedia != "undefined" || typeof window.msMatchMedia != "undefined")
    {
        // alert("media queries are supported!");
        return true;
    }else{
        // alert("no media query support :(");
        return false;
    }
}

Or more elegantly:

function mediaQueriesSupported()
{
    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

As for gradient support detection, there are some great answers here and here. Effectively you're just setting the property and then testing for it after the fact. Browsers will throw out junk or unsupported CSS properties.

EDIT:

Niet has an excellent answer to this problem over here, similar to my suggestions for gradient detection. It's not pure Javascript (it requires a very small amount of CSS) but it's an absolutely fool-proof method.

Community
  • 1
  • 1
Sandy Gifford
  • 7,219
  • 3
  • 35
  • 65
  • 4
    IE9 support the CSS media queries, but doesn't have the `matchMedia` JavaScript method. – Etienne Oct 29 '13 at 16:15
  • @Etienne I've edited my answer to cover IE9. I don't actually have a computer ready to test 9, though, so it may not work. The change brings my code closer to Modernizr's `mq` function (which checks to see if a browser supports a particular media query before trying to run it). My JSFiddle is also updated if anyone wants to try it out (for comparison, [here is the old JSFiddle](http://jsfiddle.net/3vbNb/)) – Sandy Gifford Nov 11 '13 at 18:05
  • 1
    @Sandy I am actually getting back the function and not a true or false back from the elegantly solution :) Its all good thought I used this instead:`mediaQueriesSupported = function () { return (window.matchMedia || window.msMatchMedia) ? true : false; };` – sebastian.derossi Feb 05 '14 at 21:45
  • @sebastian.derossi I'm reading over this question again and I think I see the problem. If window.matchMedia is not defined, but window.msMatchMedia is, window.msMatchMedia will return, not true or false. Good catch! – Sandy Gifford Feb 05 '14 at 22:01
  • This code gives "not supported" for IE9, although it does support media queries. Seems to work fine for other browsers. – user1702401 Mar 31 '15 at 12:36