r/javascript • • Aug 21 '18

Effectively supported in all browsers, JavaScript has its own form of media queries just like CSS.

https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
465 Upvotes

114 comments sorted by

View all comments

65

u/PortablePawnShop Aug 21 '18

Holy shit, I've been doing absurdly complicated workarounds for some of this

1

u/deadlyicon Aug 22 '18

Can’t you get everything you get from css media queries, in JS, by listening to window resize events and doing a bit of math?

14

u/mort96 Aug 22 '18

Media queries can do more than just detect the screen size; it can tell if the screen is in landscape or portrait, the screen's pixel density, the color bit depth, whether the device's input method allows the user to hover over stuff (as opposed to a touch screen, where you're either not interacting with the screen at all or clicking on something), the light level from the device's light sensor, how precise the user's pointing device is (if any), whether there's a speech synthesizer, whether the page is being printed, etc.

https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries