Checking for Reduced Motion Preference in JavaScript
Nathan
Posted on September 13, 2021
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!
Posted on September 13, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
August 16, 2024
August 4, 2024