Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

MediaQueryList: the matches property and the change event

Read `matches` to get the current result of a CSS media query, and listen for `change` to respond only when that result switches.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

const mql = window.matchMedia(mediaQueryString);

function onChange(event) {
  update(event.matches);
}

mql.addEventListener("change", onChange);
update(mql.matches);

// When observation is no longer needed:
mql.removeEventListener("change", onChange);

MediaQueryList.matches/change pairs a property for reading the current result with an event for observing later changes. Pass a CSS media query string to window.matchMedia(mediaQueryString) to get a new MediaQueryList. Its read-only Boolean matches is true if the document currently matches the query and false otherwise. The query (max-width: 600px) includes a viewport width of exactly 600 CSS pixels.

Register the callback with mql.addEventListener("change", onChange). The browser fires change on that MediaQueryList when the result switches from false to true or back, not on every resize. The callback receives a MediaQueryListEvent: event.matches holds the new result and event.media holds the query text.

Registering the listener does not call it immediately. Initialize your state by reading mql.matches, then use event.matches for later changes. When you no longer need updates, call mql.removeEventListener("change", onChange) on the same object with the same function.

This is a browser API, not part of ECMAScript 2024. Do not assume it exists in a non-browser runtime. addListener() and removeListener() are the legacy pair for compatibility; prefer addEventListener() and removeEventListener() in new code.

Examples

(async () => {
  const frame = document.createElement("iframe");
  frame.style.cssText = "display: block; width: 800px; height: 80px; border: 0";
  frame.srcdoc = "<!doctype html><title>Media query demo</title>";

  const loaded = new Promise((resolve) => {
    frame.addEventListener("load", resolve, { once: true });
  });
  document.body.append(frame);
  await loaded;

  const view = frame.contentWindow;
  // Give the browser time to render and report media query changes.
  const afterRendering = () => new Promise((resolve) => {
    view.requestAnimationFrame(() => view.requestAnimationFrame(resolve));
  });
  await afterRendering();

  const mql = view.matchMedia("(max-width: 600px)");
  const onChange = (event) => console.log(`change: ${event.matches}`);

  mql.addEventListener("change", onChange);
  console.log(`initial: ${mql.matches}`);

  for (const width of [600, 500, 800]) {
    frame.style.width = `${width}px`;
    await afterRendering();
  }

  mql.removeEventListener("change", onChange);
  frame.style.width = "600px";
  await afterRendering();
  frame.remove();
})();

Result

initial: false
change: true
change: false

Open `about:blank` in a browser and run the code in its console. The snippet resizes the iframe viewport from 800 to 600, then 500, then back to 800 CSS pixels. The step to 500 adds no log line. After the snippet removes the listener, resizing to 600 again also adds no line.

Related lessons

  • JavaScript · Lesson 29 · Advanced · Version: 4
  • JavaScript · Lesson 34 · Advanced · Version: 4
  • JavaScript · Lesson 35 · Advanced · Version: 4
  • JavaScript · Lesson 36 · Advanced · Version: 4
  • JavaScript · Lesson 37 · Advanced · Version: 4
  • JavaScript · Lesson 39 · Advanced · Version: 4
  • JavaScript · Lesson 45 · Advanced · Version: 4
  • JavaScript · Lesson 27 · Intermediate · Version: 3
  • JavaScript · Lesson 28 · Intermediate · Version: 3
  • JavaScript · Lesson 29 · Intermediate · Version: 3

Sources