How to use JavaScript for media queries

Use JavaScript for media queries

Media queries were introduced in CSS3 and are one of the key elements of responsive web design. Media queries are used to determine the width and height of the viewport to ensure that the web page displays well on all devices (desktops, laptops, tablets, mobile phones, etc.).

window.matchMedia() The method returns a MediaQueryList object that represents the result of the specified CSS media query string.matchMedia() The value of the method can be CSS @media Any media feature rule, such as min-height,min-width,orientation etc.

Example

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

function myFunction(x) {
  if (x.matches) { // If media query matches
    document.body.style.backgroundColor = "yellow";
  } else {
    document.body.style.backgroundColor = "pink";
  }
}
// Create MediaQueryList object
var x = window.matchMedia("(max-width: 700px)");
// Call listener function at runtime
myFunction(x);
// Attach listener function when the state changes
x.addEventListener("change", function() {
  myFunction(x);
);

Try it yourself

Related pages

Tutorial:CSS Media Query

Tutorial:Responsive web design

Reference manual:JavaScript window.matchMedia() method