Detecting Dark Mode with Javascript

Published on May 9, 2020

Dark mode can be detected in Javascript by using window.matchMedia() to check a match for the prefers-color-scheme: dark CSS media query.

// dark-mode media query matched or not
let matched = window.matchMedia('(prefers-color-scheme: dark)').matches;

	console.log('Currently in dark mode');
	console.log('Currently not in dark mode');

Other than the dark mode, device can be in light mode, or user may have set no preference.

  • To check for light mode, the prefers-color-scheme: light media query can be used.
  • To check for no set preference, the prefers-color-scheme: no-preference media query can be used.


Dark mode currently activated ?
In this Tutorial