How To Use Media Queries in JavaScript

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

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.