prefers
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

prefers

NPM travis-ci gzip size TypeScript

Detect system (or manually set) preferences for color scheme and reduced motion.

Works in all modern browsers and the difference to user experience is day and night! 😬


Detect color scheme

import { prefers, setPrefers } from 'prefers';

// When system preference is light
prefers('color-scheme'); // light
prefers('color-scheme', 'light'); // true

// Manually set preference (in localStorage)
setPrefers('color-scheme', 'dark');
prefers('color-scheme'); // dark
prefers('color-scheme', 'dark'); // true

// Remove manually set preference
setPrefers('color-scheme', false); // removed

// When system has no preference, fallback to default
prefers('color-scheme', 'light', true); // light
prefers('color-scheme', 'dark', true); // dark

Note: Manually set preference will take priority over system preference.

Detect reduced motion

import { prefers, setPrefers } from 'prefers';

// Assume reduced motion is turned off
prefers('reduced-motion'); // false
setPrefers('reduced-motion', 'reduce'); // turn on

// Assume reduced motion is turned on
prefers('reduced-motion'); // true
setPrefers('reduced-motion', 'no-preference'); // turn off

Tip

For the best experience it's highly recommended to check for the preference as soon as possible. For example: If you use (p)react, call it before rendering the application. This way, if you're switching CSS variables or a class, the first render will match the preference.

Other preferences?

There's a draft which describes more preferences we can possibly detect in the future. Once these actually become available, this library will include them!

Have a look at the W3C Working Draft for Media Queries Level 5.

License

MIT © Colin van Eenige

Package Sidebar

Install

npm i prefers

Weekly Downloads

4

Version

1.0.0

License

MIT

Unpacked Size

15.1 kB

Total Files

11

Last publish

Collaborators

  • vaneenige