logo
post image

How to Check for a CSS Media Query Match in Javascript

CSS media queries can be checked for a match in Javascript using the window.matchMedia() object.

Checking Match with a Media Query

// media query to check
var media_query = 'screen and (min-width:320px) and (max-width:1023px)';

// matched or not
var matched = window.matchMedia(media_query).matches;

if(matched)
	console.log('Screen is between 320 and 1023 pixels');
else
	console.log('Screen is not between 320 and 1023 pixels');

The matches() method of the window.matchMedia object will check whether a specific media query matches with the current state of the document. If the media query matches, true is returned, otherwise false.

Monitoring Page For a Media Query Change

Monitoring the page for a media query change can be done through the change event on the window.matchMedia object. This event will be triggered each time when the state of the media query changes — either the page goes into the specific media query state or it goes out of the specific media query state.

var media_query = 'screen and (min-width:320px) and (max-width:1023px)';

// event to watch the media query
window.matchMedia(media_query).addEventListener('change', function() {
	// matched or not
	var matched = this.matches;

	if(matched)
		console.log('Screen is between 320 and 1023 pixels');
	else
		console.log('Screen is not between 320 and 1023 pixels');
});