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
function myFunction(x) {
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);
});
Try it Yourself »
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).
The window.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 the CSS @media rule, like min-height, min-width, orientation, etc.
Learn more about media queries in our CSS Media Queries Tutorial
Learn more about responsive design in our Responsive Web Design Tutorial
Learn more about the window.matchMedia() method in our JavaScript Reference.