0

This function only works when the page gets reloaded:

if (window.matchMedia("(max-width: 700px)").matches) {
  $("html").css("background-color", "yellow");
} else {
  $("html").css("background-color", "red");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

But how can I additionally update it if the window size changes?

This article didn't help me so far. It's hard for me to find the best solution.

Anna_B
  • 955
  • 1
  • 10

3 Answers3

0

You could set up the event handler using the addEventListener() method:

Window.addEventListener('resize', reportWindowSize);

function reportWindowSize() {
  var height = window.innerHeight;
  var width = window.innerWidth;
}

or

window.onresize = reportWindowSize;
MD. RAKIB HASAN
  • 328
  • 1
  • 12
0

Using jQuery just put it in a resize event handler and trigger the event also when page loads

$(window).resize(function(){    
    if (window.matchMedia("(max-width: 700px)").matches) {
      $("html").css("background-color", "yellow");
    } else {
      $("html").css("background-color", "red");
    }
}).resize()// trigger on page load
charlietfl
  • 164,229
  • 13
  • 110
  • 143
0

function myFunction() {
  if (window.matchMedia("(max-width: 700px)").matches) {
    $("html").css("background-color", "yellow");
  } else {
    $("html").css("background-color", "red");
  }
};

// Resize event
window.addEventListener("resize", myFunction);

// First load
window.addEventListener("load", myFunction);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
0stone0
  • 11,780
  • 2
  • 20
  • 35