JavaScriptBrowser APIs

matchMedia()

Checks in JavaScript whether the page matches a CSS media query, e.g. (max-width: 600px), and lets you react to changes in the result.

Returns
A MediaQueryList object with matches and media properties.
On this page

Example

#
JavaScript
const mobile = matchMedia('(max-width: 600px)')
const prefersDark = matchMedia('(prefers-color-scheme: dark)')

console.log(mobile.media)
console.log(mobile.matches)
console.log(prefersDark.matches)

if (!mobile.matches) {
  console.log('Showing the full menu with section names')
}
Result
(max-width: 600px)
false
true
Showing the full menu with section names

The result is for a wide window on a computer with the system’s dark theme turned on. On a phone, mobile.matches is true. The result depends on the device, so this example doesn’t run in the preview.

Definition and usage

#

The matchMedia() function (its full name is window.matchMedia()) takes a media query in the same form as an @media rule in CSS and returns a MediaQueryList object. Its matches property is true when the condition is met, and media holds the query’s text. This lets you check the window’s width, the screen’s orientation, or the user’s preferences.

The object fires a change event every time the query’s result changes, e.g. when the user narrows the window past a threshold or switches the system to dark mode. You handle it with addEventListener("change", …), and the event object also has a matches field. This is more efficient than checking window.innerWidth on every resize event, because the function only fires when a threshold is crossed.

Queries about preferences are especially useful: (prefers-color-scheme: dark) tells you whether the system uses a dark theme, and (prefers-reduced-motion: reduce) whether the user asked to limit animations. It’s worth taking these into account in scripts that animate elements themselves or choose the page’s theme.

Syntax

#
Syntax
window.matchMedia(mediaQueryString)

mediaQueryList.matches
mediaQueryList.media
mediaQueryList.addEventListener("change", listener)

Parameters

#
  • mediaQueryString

    string

    A media query written like in CSS, e.g. "(max-width: 600px)" or "(prefers-color-scheme: dark)".

More examples

#
Reacting to a width change
JavaScript
const nav = document.querySelector('#nav')
const narrow = matchMedia('(max-width: 600px)')

function updateNav(query) {
  nav.textContent = query.matches ? 'Menu ☰' : 'Courses · Ranking · Profile · Settings'
}

updateNav(narrow)
narrow.addEventListener('change', updateNav)

console.log('Listening for changes:', narrow.media)
Console
Listening for changes: (max-width: 600px)

The menu’s content depends on the width of the frame holding the example. Narrow or widen the browser window so the frame crosses 600 px, and the menu switches on its own, without listening for the resize event.

Limiting animation at the user’s request
JavaScript
const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)')

function scrollToTop() {
  window.scrollTo({ top: 0, behavior: reduceMotion.matches ? 'auto' : 'smooth' })
}

console.log(reduceMotion.matches ? 'Scrolling without animation' : 'Smooth scrolling')
Result
Smooth scrolling

Most people don’t have reduced motion turned on, so you’ll usually see this result. After enabling reduced motion in the system settings, matches becomes true, and the page scrolls without animation.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Use addEventListener("change", …) to react to changes. The older addListener() method is deprecated.
  • Keep width thresholds in scripts in sync with the breakpoints in CSS. Otherwise, at the same width, the script and the styles might behave differently.
  • Change the look itself in CSS with @media. matchMedia() is useful when logic depends on the query, e.g. whether to turn on an animation or which component to show.

Related entries

#

Spotted a mistake or missing an example? Write to us.