0
With the help of W3SCHOOL I was able to create this code that inserts an html through Javascript. I also need a specific code to be shown if <700 and other code is displayed if >701. The code below does not work 100% because when resizing the window it does not update. To work 100% you need to refresh the page. What is the correct way to use Media Query with Javascript?
<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>
Wouldn’t it be simpler to use one media query directly by CSS? What is the need to do it using Javascript?
– Luiz Felipe