Sign in
Log inSign up

Checking for Reduced Motion Preference in JavaScript

Nathan's photo
Nathan
·Sep 13, 2021·

1 min read

When animating elements with CSS, you can use a snippet such as the following to disable animations for users with browsers that request reduced motion:

@media (prefers-reduced-motion: reduce) {
    * {
        animation: none !important;
        transition-duration: 0s !important;
    }
}

However, some fancier animations actually require JavaScript effects.

You can still disable those animations for users that request it by checking for those requests using the following code:

const isReduced = window.matchMedia(`(prefers-reduced-motion: reduce)`) === true || window.matchMedia(`(prefers-reduced-motion: reduce)`).matches === true;

if (!!isReduced) {
    // DON'T use an amination here!
} else {
    // DO use an animation here!
}

And that's about it! The media matching function is an extremely powerful built-in feature supported by most browsers, and this is just one of the many excellent use cases for it.

Conclusion

I hope you enjoyed this brief little tutorial. It's just a few lines of code that can make a massive impact on the experience of some of your users (probably more than you might expect, in fact).

Thanks for reading!

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct