Dark mode implementation using .js fundamentals

As every other app and OS is embracing the dark mode, here is a simplistic approach that I used to implement it using plain javascript and css to implement a configurable dark mode on a web app.

All the UI components have pre-configured css classes associated with them. One each for each mode. The components are dynamically switched from 1 class to another based on two triggers:

  • User switches the display mode
  • The display mode switches based on a pre-set time trigger

The toggleBackgroundColor() when invoked, toggles the mode. It is called when user initiates mode-change.

The timer call back timeoutTriggered() is set with for the time to next desired mode change pre-set time.

Current time:           18:20  (66,000,000 ms)
Dark mode trigger time: 21:00  (75,600,000 ms)
Timer call back:        9600000 ms

Each time it is invoked,

  1. It invokes toggleBackgroundColor() to change the display mode
  2. It looks forward for the next pre-configured desired mode change and sets a timer call back.

When the pre-set time is changed from UI,

  1. The associated timer call back is scrubbed using clearTimeout(timer) method.
  2. It computes and sets a new timer call back

In Action