How to use media queries with JavaScript?


To use media queries with JavaScript, the code is as follows −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      color: white;
      padding: 20px;
   }
</style>
</head>
<body>
<h1>Using media queries with JavaScript Example</h1>
<h2>Resize the screen to see the color change from blue to red</h2>
<script>
   var mediaQuery = window.matchMedia("(max-width: 700px)");
   function setColor(mediaQuery) {
      if (mediaQuery.matches) {
         document.body.style.backgroundColor = "red";
      } else {
         document.body.style.backgroundColor = "blue";
      }
   }
   setColor(mediaQuery);
   mediaQuery.addListener(myFunction);
</script>
</body>
</html>

Output

The above code will produce the following output on window size greater than 700px −

On resizing the browser window size less than 700px −

Updated on: 12-May-2020

257 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements