How to Check for a Media Query Match in Javascript

Use-Cases of this Tutorial

  • You are looking to know if there is a media query match through Javascript code.
  • You are looking to maintain responsiveness through Javascript.

Media queries are mostly used in CSS while creating responsive web applications.

/* apply CSS styles when screen width is between 320px and 1023px */
@media screen and (min-width:320px) and (max-width:1023px) {
	font-size: 1.2em;
}

In rare cases we may need to execute some Javascript code depending on the current screen size, screen pixel ratio — basically depending on a specific media query. This can be done with the help of window.matchMedia object.

window.matchMedia takes a specific media query as parameter and returns a MediaQueryList object. Methods and events can then be applied on this object to detect match with the given media query.

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

var media_query_list = window.matchMedia(media_query);

Checking Match with a Specific Media Query

The matches method 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.

// 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');

Detecting Change in Matching State of a Specific Media Query

Sometimes we would even like to keep detecting change in success state of a specific media query — for example we would like to monitor the change in specific screen size each time.

This can be done through the change event. This event will be triggered each time when the state of the media query changes — either the screen 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');
});

this inside the event listener refers to the MediaQueryList object.