Matching Media Queries

matchMedia(query) evaluates a CSS media query (@media) from JavaScript and returns a MediaQueryList with media (the normalized query), matches, and a change event that fires only when matches flips. Use it for behavior CSS cannot express, such as loading a chart only on wide screens.

Tracking a media query from a scriptHTMLLive
<p id="out"></p>
<script>
  const wide = matchMedia('(min-width: 600px)');
  const out = document.querySelector('#out');
  const show = () => { out.textContent = `${wide.media}: ${wide.matches}`; };
  wide.addEventListener('change', show);   // not the deprecated addListener()
  show();
</script>
Browser output of Listing 8.10
Browser output of 10

The 480-pixel viewport fails the query; widen the window and the text updates. That is cheaper than a resize listener, which fires continuously while the user drags.