Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS determining active media query

In Javascript is there a direct way (not involving parsing the css code) to determine which media query is active?

For instance I have two queries:

 @media screen and (max-width:800px)

 @media screen and (min-width:801px)

without parsing and looking at the clientWidth, how can I tell which one of these has evaluated to true.

like image 945
freddylindstrom Avatar asked Mar 28 '11 14:03

freddylindstrom


1 Answers

Though this is an old question it ranks highly when googling for this problem.

Window.matchMedia is official and is supported by all major browsers (IE10+) and will allow you to query if a certain media query currently matches.

From the original question:

if (window.matchMedia('screen and (max-width:800px)').matches) {
    // it matches
} else {
    // does not match
}

You can also listen for when the query match result changes by attaching an event listener to the MediaQueryList that window.matchMedia returns:

var mql = window.matchMedia('screen and (max-width:800px)');
mql.addEventListener(
    function(mq) {
        if (mq.matches) {
            // it matches
        } else {
            // does not match
        }
    }
);
like image 84
Pete Avatar answered Sep 29 '22 16:09

Pete