Detect and support user preferences with AlpineJS
As a fan of user preferences, I love to take the opportunity to support user customization any way I can. Check out my site's customization toolbar in the bottom left of the screen!
For this site, I have elevated dark mode and reduced motion to persist across page loads for a better user experience. Here's how this site detects and implements them with AlpineJS:
<body
x-data="{
adaptive: $persist(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches),
motionReduce: $persist(window.matchMedia && !window.matchMedia('(prefers-reduced-motion: reduce)').matches),
}"
:class="{
'adaptive': adaptive == true,
'motion-reduce': motionReduce == true,
'motion-safe': motionReduce == false,
}"
>