Window matchMedia() Method - If the viewport is <=700 pixels wide, change the background color to yellow. - Javascript Browser Object Model

Javascript examples for Browser Object Model:Window matchMedia

Description

Window matchMedia() Method - If the viewport is <=700 pixels wide, change the background color to yellow.

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<script>
function myFunction(x) {//  www  .j a  va2s .  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>

Related Tutorials