weilou
weilou

Reputation: 4617

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

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.

Upvotes: 2

Views: 5145

Answers (1)

Sandy Gifford
Sandy Gifford

Reputation: 8136

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.

Upvotes: 14

Related Questions