How to use media queries with JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

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


 Live Demo

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


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 12:21:04