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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

IE9 support the CSS media queries, but doesn't have the matchMedia JavaScript method.
@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)
@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 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!
This code gives "not supported" for IE9, although it does support media queries. Seems to work fine for other browsers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.