How TO - Media Queries with JavaScript
Example
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
if (x.matches) { // If media query matches
document.body.style.backgroundColor = "yellow";
} else {
document.body.style.backgroundColor = "pink";
}
}
// Create a MediaQueryList object
var x = window.matchMedia("(max-width: 700px)")
// Call listener function at run time
myFunction(x);
// Attach listener function on state changes
x.addEventListener("change", function() {
myFunction(x);
});
Using Media Queries With JavaScript
Media queries was introduced in CSS3, and is one of the key ingredients for responsive web design. Media queries are used to determine the width and height of a viewport to make web pages look good on all devices (desktops, laptops, tablets, phones, etc).
Thewindow.matchMedia() method returns a MediaQueryList object representing the results of the specified CSS media query string.The value of the matchMedia() method can be any of the media features of theCSS @media rule, like min-height, min-width, orientation, etc.
Learn more about media queries in ourCSS Media Queries Tutorial
Learn more about responsive design in ourResponsive Web Design Tutorial
Learn more about thewindow.matchMedia() method in our JavaScript Reference.

