CKTIS / JavaScript
window.matchMedia — testing media queries
window.matchMedia tests a CSS media query from JavaScript. It returns a MediaQueryList with the current matches result and lets you observe changes in whether the query matches.
Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support
Syntax
const mql = window.matchMedia(query);
mql.matches;
mql.media;
mql.addEventListener("change", handler);
mql.removeEventListener("change", handler);window.matchMedia(query) creates a new MediaQueryList, not a boolean. Read matches for the current result; media contains the serialized query.
Pass a CSS query such as "(min-width: 768px)", without @media. The width media feature refers to the width of the viewport in continuous media and to the width of the page box in paged media such as print. The unit px means CSS pixels. This query is not restricted to the screen media type. The method tests a condition; it does not apply styles itself.
This is a CSSOM View browser API, not an ECMAScript feature. Before calling window.matchMedia(query), check typeof window !== "undefined" && typeof window.matchMedia === "function"; Node 24 alone does not prove support. This check does not test for event listener methods on the returned object.
Read the initial result from mql.matches, where mql is the returned MediaQueryList. Register the handler with mql.addEventListener("change", handler) only if typeof mql.addEventListener === "function" && typeof mql.removeEventListener === "function". If either method is missing, skip registration; you can still read matches. The event signals a changed result, not every resize; event.matches provides the new result. If you registered the handler, call mql.removeEventListener("change", handler) with the same function during cleanup.
The example uses all and its negation not all, making the output independent of window size.
Examples
const always = window.matchMedia("all");
const never = window.matchMedia("not all");
console.log(always.matches);
console.log(never.matches);Result
true false
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.