Detecting Device Dark Mode setting

Dark mode means different things to different people. But light vs dark mode boils down to 2 color schemes. Most system defaults for light and dark are based on white and black for lettering vs background. However, application users may be looking for other options. For example, the warfighter doesn’t want to be seen during night operations, so dark mode would be really dark. But others who change colors for eye strain may not get it with white/black or black/white contrasts. So, I think it’s up to the developer to decide what is the best color schemes for light and dark, or whatever you call your modes if you do implement this.

Here’s the code to see what the user set in the device. Note, the first two provide the same information. Too bad we can’t just read the media values directly :astonished:

Button3.onclick=function(){
  alert("prefers-color-scheme media is used by device: " + window.matchMedia('(prefers-color-scheme)').matches);
  alert("prefers-color-scheme media does not exist if returns .media of:  not all  : " + window.matchMedia('(prefers-color-scheme)').media);
  alert("prefers-color-scheme is set to light: " + window.matchMedia('(prefers-color-scheme: light)').matches);
  alert("prefers-color-scheme is set to dark: " + window.matchMedia('(prefers-color-scheme: dark)').matches);
  alert("prefers-color-scheme is set to no-preference: " + window.matchMedia('(prefers-color-scheme: no-preference)').matches);
}

To detect the change of light/dark mode change by the user/device in real time, use something like this in the Main of your project:

// media query event handler
if (matchMedia) {
  var mq = window.matchMedia('(prefers-color-scheme: dark)');
  mq.addListener(DarkChange);
  DarkChange(mq);
}

// media query change
function DarkChange(mq) {
  SetDarkModeTheme(mq.matches);
}

function SetDarkModeTheme(IsDark) {
if (IsDark) {
  // set dark mode here
  } else {
  // set light mode here
  }
}