This site runs best with JavaScript enabled.

Media Queries in JavaScript

Kevin Beck

October 15, 2019


The matchMedia() method returns a new MediaQueryList object that gives us the results of the specified media query string ('(max-width: 600px)' or '(min-width: 1200px)').

With the retuned MediaQueryList we can determine if the Document matches the specified media query or to watch to see when it matches or stops matching the specified media query.

var mediaQueryString = '(max-width: 600px)';
function yourFunction() {
// do something when then retuned MediaQueryList() object changes
}
matchMedia(mediaQueryString).addEventListener('change', yourFunction);

Reference

Source