Javascript Browser Window matchMedia() Method handle media query event

Introduction

If the viewport is less than, or equal to, 700 pixels wide, change the background color to yellow. If it is greater than 700, change it to pink

View in separate window

<!DOCTYPE html>
<html>
<body>
<p>Resize the browser window to see the effect.</p>

<script>
function myFunction(x) {//  ww  w  . ja  va 2  s.c  o  m
  if (x.matches) { // If media query matches
    document.body.style.backgroundColor = "yellow";
  } else {
    document.body.style.backgroundColor = "pink";
  }
}

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>

</body>
</html>



PreviousNext

Related