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

-34

u/StoneCypher Aug 21 '18

um, this actually is css, not javascript

0

u/[deleted] Aug 21 '18

[deleted]

-33

u/StoneCypher Aug 21 '18

Seems to work as expected

<html><head><style type="text/css">
  @media (min-width: 400px) { body { background-color: green; } }
  @media (max-width: 399px) { body { background-color: red; } }
</style></head><body>
  <p>hiya</p>
</body></html>

14

u/rabidhamster Aug 22 '18

Which is not even close to what was asked of you. The only thing that matches is the "min-width: 400px". The rest of the syntax is entirely different.

Try this in your CSS:

if (window.matchMedia("(min-width: 400px)").matches) {
  console.log('Larger than 399px');
} else {
  console.log('Less than 400px');
}

See how media queries based in JavaScript might have some utility and use-cases beyond what CSS can provide?

-16

u/StoneCypher Aug 22 '18

I think that you are confusing "I can use css from Javascript" with "this must not be css"

11

u/rabidhamster Aug 22 '18

Except that this isn't necessarily about styling the page. You can run different conditional branching, loops, JSON queries to the server, etc. based on the results of the window width. Just because you personally would use it to make style changes doesn't make it inherently CSS. By that logic, Javascript is just FORTRAN, because they both have "if" statements.

-12

u/StoneCypher Aug 22 '18

OK, try putting some Fortran in there and see what happens

13

u/rabidhamster Aug 22 '18

Uh, it won't work, which is precisely my point: Media queries in JavaScript are not CSS, just as JavaScript is not FORTRAN despite sharing a few basic similarities. I'm not even sure what you're arguing at this point.

-13

u/StoneCypher Aug 22 '18

Except, of course, media queries as defined in css work here

If you are not sure what my point is, it seems weird that you keep saying that I'm wrong

Have a nice day