matchMedia reads a CSS media query from JavaScript and updates the page when the preference changes.

Program

matchMedia connects JavaScript to media query state such as viewport width or color scheme preference.

match_media_theme.html
Visuals: captured from real browser rendering
<main id="shell" class="panel">Theme follows system</main>
<script>
  const shellEl = document.querySelector("#shell");
  const query = matchMedia("(prefers-color-scheme: dark)");
  function apply(event) {
    shellEl.dataset.scheme = event.matches ? "dark" : "light";
  }
  apply(query);
  query.addEventListener("change", apply);
</script>
  1. Create a media query object.

    JavaScript receives a live object for the CSS media query.
    JavaScript receives a live object for the CSS media query.
  2. Map the match result into page state.

    The current system preference becomes a data attribute.
    The current system preference becomes a data attribute.
  3. Apply the current query value.

    The first render uses the current media query value.
    The first render uses the current media query value.
  4. Listen for preference changes.

    Future system theme changes will re-run apply.
    Future system theme changes will re-run apply.
matchMedia matchMedia evaluates a CSS media query from JavaScript.
change event A media query list can notify code when its matches value changes.