1

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.

1
  • document.styleSheets[i].media[j] Commented Mar 14, 2012 at 6:59

1 Answer 1

2

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.

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

2 Comments

Any ideas of "invisible" styles I could use hinting, e.g. on <body>? The styles which would not affect layout, but become readable via getComputedStyles()?
You can use a div that is positioned absolutely with a left: -1000px. Because it's position: absolute, it won't affect the layout of the page. Because it's left: 1000px, it won't be visible and won't cause scrollbar. Then, set a CSS width on it with a media query rule and you can read that width with getComputedStyles(). jQuery uses this trick to calclulate things when it needs something laid out by the browser, but not visible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.