Settings

Theme

Show HN: A Dark Mode Toggle Without JavaScript

tymekdev.github.io

4 points by TymekDev 2 years ago · 5 comments · 1 min read

Reader

Today I scratched my itch of implementing a dark mode toggle without JacaScript. The implementations I saw typically revolved about adding a 'dark' class to body via JS and then controlling it with JS handlers.

Thanks to `:has()` selector [0], that passed 90% browser compatibility [1], it is possible to avoid JS.

My implementation uses CSS variables combined with a checkbox, `:checked`, and `:has()`. It is simple, yet supports color scheme preference and updates toggle's label based on active mode.

[0]: https://developer.mozilla.org/en-US/docs/Web/CSS/:has

[1]: https://caniuse.com/css-has

DHPersonal 2 years ago

This is really cool and a great example of the upgrades to CSS. The benefit of JavaScript would be setting a state in localStorage to remember the light/dark value that was set, as yours does not remember what was set after a shift+f5 refresh of the site.

  • TymekDevOP 2 years ago

    With JavaScript you could make it a three state toggle: light, dark, and auto. The last one would allow to to back to the default - no preference.

    I thought this might use indeterminate checkbox, but that wouldn't be necessary. 'Light', 'dark', and lack of thereof in localStorage already amount to three distinct states.

numtel 2 years ago

I'm sure it'll make it to Firefox for Android soon. I would imagine these "in page" toggles will fade away as the OS makes the switcher more prominent. In Gnome, it's right in the main menu next to the volume.

  • TymekDevOP 2 years ago

    It's already there in Firefox for Android! If you take a look at MDN, it states it's available since 121 that released on 2023-12-19.

    In fact, I am using it right now, and the example works without issues.

baobaba 2 years ago

Thanks for sharing! Very cool.

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection