R
R
Rafael™2016-04-14 09:31:30
JavaScript
Rafael™, 2016-04-14 09:31:30

JS alternative to media query?

instead of a media query, it is quite possible to check the screen size on js and connect the desired style
, it seems to me that this is quite a good alternative -
this is how imperative programming is used instead of declarative
and the result is the same
how often is this method used in nature?
what are the disadvantages of this method?

if (window.matchMedia("(min-width: 400px)").matches) {
  /* the viewport is at least 400 pixels wide */
} else {
  /* the viewport is less than 400 pixels wide */
}

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
Alexander, 2016-04-14
@lasmaster

The best practice is NOT to use JS if it is possible to implement this functionality with CSS. The performance of CSS is many times higher than JS.

G
GreatRash, 2016-04-14
@GreatRash

You can also set media qveri in JS. But in general, nothing prevents stupidly looking at the width of the window.

A
Alexey Ukolov, 2016-04-14
@alexey-m-ukolov

this is how imperative programming is used instead of declarative
Here is your disadvantage.
Instead of delegating the dumb work to the browser, you do it yourself.
how often is this method used in nature?
Only when there is no other way out.

K
Konstantin, 2016-04-14
@constantant

how often is this method used in nature?

It all depends on the task and the browser. If you want a special dependency, then implement it through JS, something simple through media queries.
It probably just takes longer to implement. Performance, if you hint at it, depends on the implementation, so it’s impossible to say for sure

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question