Search code examples
javascriptcssmedia-queries

Accessing CSS3 media queries from Javascript


Now, finally after 12 years, when all the world is hopping into CSS3 media query and responsive design bandwagon a problem remains.

How one can know from Javascript which media queries are

  • present in HTML code: this should be simple element traversing, but are there smarter ways?

  • effective (query evaluates to true)

... so you can add special code paths to support mobile, tablets, etc. in Javascript code? Eventually one could write function isMobile() and use it as a flag for certain actions specific to small screen estate.


Solution

  • It is possible to have a specific object in your page that gets a known style from your CSS for each media query of interest. You can then read that style off the object with getComputedStyle() and see what was assigned to it and that would tell you which media query had precedence.