0

The code is not working 100%. Only works if I reload the page. I want that some code turn visible if "size < 700" and other code turn visible if the "size > 699".

I tryed this code also http://www.javascriptkit.com/dhtmltutors/cssmediaqueries4.shtml

<script>
function myFunction(x) {
  if (x.matches) { // If media query matches

/* === código html === */
var mb = document.createElement("div"); /* cria DIV */
mb.setAttribute("class", "conteiner"); /* seta a class="banner" para a DIV */

mb.innerHTML = /* ESTRUTURA html */
"<div class='secao-principal row-fluid sem-coluna'> " +
"<div class='row-fluid'> " +

"<div class='modulo span3'> <a href='' > <img src='https://picsum.photos/id/156/404/260?blur=5' alt=''/> </a> </div>" +
"<div class='modulo span3'> <a href='' > <img src='https://picsum.photos/id/156/404/260?blur=5' alt=''/> </a> </div>" +
"<div class='modulo span3'> <a href='' > <img src='https://picsum.photos/id/156/404/260?blur=5' alt=''/> </a> </div>" +
"<div class='modulo span3'> <a href='' > <img src='https://picsum.photos/id/156/404/260?blur=5' alt=''/> </a> </div>" +


"</div>" +
"</div>";       

var list = document.getElementById("corpo");
list.insertBefore(mb, list.firstChild);

} else {

/* === código html === */
var mb = document.createElement("div"); /* cria DIV */
mb.setAttribute("class", "conteiner"); /* seta a class="banner" para a DIV */

mb.innerHTML = /* ESTRUTURA html */
"<div class='secao-principal row-fluid sem-coluna'> " +
"<div class='row-fluid'> " +

"<div class='modulo span3'> <a href='' > <img src='https://picsum.photos/id/156/404/260?blur=5' alt=''/> </a> </div>" +


"</div>" +
"</div>";       

var list = document.getElementById("corpo");
list.insertBefore(mb, list.firstChild);


}
}
var x = window.matchMedia("(max-width: 700px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes



</script>

I expect the media query works always the browser is resized

4b0
  • 21,981
  • 30
  • 95
  • 142

1 Answers1

0

I'm pretty sure you would need to set a window EventListener for resize and call matchMedia each time it is updated (might want to throttle the eventListener however as it really only needs to be updated every 50-100ms or so)

There's an excellent library for doing media queries in Javascript called Enquire.js and if you don't want to use the full package you could inspect the project src on github to help out with your particular use case?

https://wicky.nillia.ms/enquire.js/

Jon B
  • 2,444
  • 2
  • 18
  • 19