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.
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
}
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With