Custom nerdlet get theme preferences

Custom nerdlet get theme dark/light preferences

Description
Is there a way to detect when the user changes the theme to dark/light?
I am working with a custom nerdlet and I want to define different styles for a dark theme.

For example, I have some elements in green color that looks good on light theme, but when I switch to dark theme it doesn’t looks good, and I would like to change that to white, so it can be readable.

1 Like

@dpena Another great question and I’m going to tag some of our nerdlet SMEs to see if they know: @dgolden / @mfrederick

@dpena
Dark Mode was recently released, and is still developing and evolving. At this point in time there is not a platform/programmability provided way to determine if a user has activated dark mode or not. I suspect this will improve over time.

Depending on your tolerance for unofficial/unsupported means of determining dark mode - I noticed that we add a class to the window’s html element when Dark Mode is “on”. You could use this to progressively enhance your app, but keep in mind it could change over time, potentially in a backwards incompatible way.

const isDarkMode =
      document
        .getElementsByTagName('html')[0]
        .classList.value.indexOf('theme-dark-fallback') >= 0;

There may be better ways/implementations as well, this was just the first I discovered. If I find more I’ll post back here!

2 Likes