What is the equivalent of the average CSS queries in Javascript?

5

When I want to apply a certain style to the size of the screen, I usually use the CSS media queries.

Example:

@media only screen and (max-width : 768px) {

    .container {
       width:960px;
    }

}

I would like to know if there is anything similar to these CSS features in Javascript.

    
asked by anonymous 06.11.2017 / 16:10

3 answers

9

You can use the Window.matchMedia () for this. See the example below.

if (window.matchMedia("(min-width:800px)").matches) {
  /* a viewport tem pelo menos 800 pixels de largura */
  console.log('a viewport tem pelo menos 800 pixels de largura')
} else {
  /* a viewport menos que 800 pixels de largura */
  console.log('a viewport menos que 800 pixels de largura')
}
  

About media print, there was a bug in the Firefox version 13 .

References:

06.11.2017 / 16:36
1

You can check the screen size and make changes with css, see:

document.getElementById("demo").innerHTML =
"Screen Width: " + screen.width;

//tamano da tela
var size = screen.width;


if(size < 3000){
    document.getElementById("demo").style.color = "blue";
  }
#demo{
  color: red;
}
<div id="demo"></div>
    
06.11.2017 / 16:19
1

I think you do not have an equivalent solution in javascript, but there are ways to get convenient results.

The first form would be the combination of the event that detects changes in the width of window , along with a check of the desired width:

window.onresize = function(event) {
  if (window.innerWidth < 768) {
    console.log("Largura da janela menor que 768 px");
  }
};

The second way would be to use the window.matchMedia method, according to example below:

if (window.matchMedia("(min-width: 500px)").matches) {
  console.log("A viewport tem pelo menos 500 pixels de largura");
} else {
  console.log("A viewport tem menos que 500 pixels de largura");
}

And through this question on SOen , I discovered that there is a plugin with the proposal to do the equivalent of CSS media queries in javascript:

link

    
06.11.2017 / 16:42