Skip to content

Instantly share code, notes, and snippets.

@dhbalaji
Last active July 23, 2021 07:33
Show Gist options
  • Save dhbalaji/bf1db51cced18899c1a7517c35407d49 to your computer and use it in GitHub Desktop.
Save dhbalaji/bf1db51cced18899c1a7517c35407d49 to your computer and use it in GitHub Desktop.
Detect Dark Mode in Javascript & media query css

Detect Dark Mode in Javascript & Media Query CSS

Problem Context

Most operating systems have a setting to set the apps background to dark colors. This is done to reduce the eye strain. Web apps can detect the OS setting and adjust the application colors accordingly. This is an UX enhancement which we can showcase.

Solution

Javascript code to detect dark mode

/**
 * Should return true when dark mode enabled
 * Should return false when dark mode disabled
 * @returns {boolean}
 */
export const checkIfDarkModeEnabledOnClientDevice = () => {
    if (window && window.matchMedia) {
        return window.matchMedia('(prefers-color-scheme: dark)').matches
    }
    return false
}

Dark mode can be detected through media query, its easy and it does not need a page refresh.

@mixin dark-mode {
  @media (prefers-color-scheme: dark) {
    @content;
  }
}

To use it

@include dark-mode {
  background-color: $darkModeBackgroundColor;
  color: $textColorDarkMode;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment