Course contentsShow
← Web Development
Lesson 556 of 2,9829. CSS Transitions and AnimationsFree lesson

JavaScript Detection of Motion Preferences

Use window.matchMedia to detect and respond to reduced motion preferences in JavaScript.

JavaScript Detection of Motion Preferences

What you'll learn: How to use JavaScript to detect whether a user prefers reduced motion and adapt your animations accordingly.

Why Detect Motion Preferences in JavaScript?

You've already learned to use the prefers-reduced-motion media query in CSS to respect user preferences. But sometimes you need to control animations through JavaScript—perhaps you're using requestAnimationFrame, toggling animation states, or deciding whether to initialize an animation library. For these cases, you need to detect motion preferences directly in your JavaScript code.

Using window.matchMedia()

The window.matchMedia() method allows you to query media features from JavaScript, just like you would in CSS. It returns a MediaQueryList object that tells you whether the query matches:

const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');

if (prefersReducedMotion.matches) {
  // User prefers reduced motion
  console.log('Reduced motion enabled');
} else {
  // User has no motion preference or prefers motion
  console.log('Full motion enabled');
}

Listening for Changes

Users can change their motion preferences without refreshing the page. You can listen for these changes:

const motionQuery = window.matchMedia('(prefers-reduced-motion: reduce)');

function handleMotionChange(event) {
  if (event.matches) {
    // Switch to reduced motion
    console.log('Reduced motion now active');
  } else {
    // Switch to full motion
    console.log('Full motion now active');
  }
}

motionQuery.addEventListener('change', handleMotionChange);

This lets your animations respond dynamically to accessibility settings.

Key Takeaway: Use window.matchMedia('(prefers-reduced-motion: reduce)') to detect motion preferences in JavaScript, and listen to its change event to respond when users update their settings.