Checking for Reduced Motion Preference in JavaScript
- 1 minute 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!