CKTIS / JavaScript
Window.matchMedia and MediaQueryList.matches
Check whether a CSS media query currently matches in JavaScript, and respond only when the match result changes.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const mediaQueryList = window.matchMedia(mediaQueryString);
const matchesNow = mediaQueryList.matches;window.matchMedia(query) takes a CSS media query string and returns a new MediaQueryList object on each call, not a boolean. Pass the query itself, without @media or a rule block. Put media feature conditions in parentheses: (max-width: 600px) tests whether the viewport is at most 600 CSS pixels wide, including the boundary.
Read list.matches without parentheses. It is a read-only boolean: true if the media query list is empty or if the document currently matches at least one query in the comma-separated list, and false otherwise. A false result does not tell you that the syntax was invalid. Reading the same object again gives you the current result; a boolean you saved earlier does not update on its own.
If you need the initial state, read list.matches, then use list.addEventListener("change", handler) for later updates. The event fires when the result flips between true and false, not on every resize. Read the new result from event.matches. When you no longer need updates, call list.removeEventListener("change", handler) with the same function.
This is a browser API, not part of ECMAScript 2024. Do not assume it is available when code runs outside a browser window. If you only need to change styles, use CSS @media: matchMedia() does not apply styles by itself.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>matchMedia example</title>
</head>
<body>
<script>
console.log(window.matchMedia("all").matches);
console.log(window.matchMedia("not all").matches);
</script>
</body>
</html>Result
true false
Open the HTML file in a browser and check the developer console. `all` matches every medium and `not all` matches none, so the output is `true` followed by `false` regardless of the viewport width.
Related lessons
- JavaScript · Lesson 3 · Advanced · Version: 4
- JavaScript · Lesson 6 · Advanced · Version: 4
- JavaScript · Lesson 7 · Advanced · Version: 4
- JavaScript · Lesson 19 · Advanced · Version: 4
- JavaScript · Lesson 41 · Intermediate · Version: 3
- JavaScript · Lesson 42 · Intermediate · Version: 3
- JavaScript · Lesson 43 · Intermediate · Version: 3