JavaScript dark mode: detect the user’s colour scheme

JavaScript dark mode: detect the user’s colour scheme

This JavaScript snippet detects whether the user has set their machine to dark mode. If they have, it returns true. It is a small piece of code that can improve your website or your application by making it friendlier to everyone who prefers a dark interface.

JavaScript Dark Mode

javascript
const isDarkMode = () =>
	globalThis.matchMedia?.("(prefers-color-scheme:dark)").matches ?? false;

// Usage
isDarkMode();

What is dark mode?

Dark mode is a feature that switches your device’s colour palette to a darker shade. Plenty of people prefer it, because it cuts down eye strain and makes text on screen easier to read. Dark mode is available on many devices, smartphones, laptops and tablets included.

If you build applications in JavaScript, offering a dark mode makes your users more comfortable while they are using what you built.

How do you turn dark mode on and off?

Here is how to enable dark themes on the most common devices and applications, with Windows, Android, Mac and iOS:

Windows

  1. From the Start menu, pick Settings then Personalisation.
  2. Select the Background option on the left of the screen. You can upload your own dark theme, or choose one supplied by Windows.
  3. Select the Colours option on the left of the screen. You can pick a colour that is easier on the eye, such as grey, tan, or a muted yellow or blue (your call).
  4. Test your colour choice in the dark theme by clicking Dark under Choose your default app mode. If you do not like the colours you picked, try something else.

Android

  1. Go to Settings, then Accessibility, then Display.
  2. Tap Dark theme to apply it, or Colour inversion to apply that instead.

MacOS

  1. Go to System Preferences.
  2. Click General.
  3. Choose the appearance option that suits you best. There are light, dark and auto options, auto following the time of day.

iOS

  1. Go to Settings.
  2. Select Display & Brightness.
  3. Switch dark mode on or off.

Conclusion

Dark mode brings real comfort to your users, and adding it to your applications is a genuine plus, not a detail.

If you are after more JavaScript articles and tips, have a look at my JavaScript articles.

JavaScript

Damien Flandrin Web developer since 2010, creator of Gekkode and Email Impact. Every article is tested on a real project before publication. Contact
Newsletter

New tests, tutorials and projects, by e-mail.

Reproducible tests, versioned code, dated results. Never any spam.