How to detect dark mode using JavaScript

Use JavaScript to detect dark mode and detect mode changes

Using CSS, we can useprefers-color-schemeMedia inquiries.

But... what if we have to use JavaScript? I recently stumbled on this problem because I have some JavaScript code to add images to the page, but I want to display different images based on the light and dark mode.

This is our approach.

First, detectmatchMediaThe object exists (otherwise the browser does not support dark mode, you can fall back to light mode).

Then, use the following command to check if it is in dark mode

window.matchMedia('(prefers-color-scheme: dark)').matches

This will returntrueIf dark mode is enabled.

This is a complete example. If the image is in dark mode, I invert the color of the image:

const img = document.querySelector('#myimage')
if (window.matchMedia && 
    window.matchMedia('(prefers-color-scheme: dark)').matches) {
  img.style.filter="invert(100%)";
}

However, there is a question: what if the user changes the mode while using our website?

We can use event listeners to detect mode changes as follows:

window.matchMedia('(prefers-color-scheme: dark)')
      .addEventListener('change', event => {
  if (event.matches) {
    //dark mode
  } else {
    //light mode
  }
})

Download mine for freeJavaScript beginner's manual


More js tutorials: