A Light/Dark Mode Switcher With System Preferences
Head's Up
There's some weird attempts at accessibility in here right now. I'm still learning what I'm doing with that so consider this a work in progress for now.
Introduction
I'm building out an example site for my Neopoligen1 website builder. It'll act as the default "getting started" site. I'm putting in several things to make it easier to get up and running for folks who don't have experience with websites yet. One of those things is a light/dark mode switcher. This page is where I'm building and testing that functionality.
Make it a web component that can be included with a default set of components for the site
Make sure it's accessible
Start by reading the value from the system if one was defined
Show what the current system value is
Default to light mode if no system settings was detected
Provide the ability to manually toggle between dark and light mode
Provide the ability to fall back to using the system preferences (if they're available otherwise fallback to light mode)
Store your setting so it sets itself when you visit the site in another session
The Code
Here's what I've got so far.
html
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur
venenatis, sem at laoreet facilisis, sapien nisi tincidunt purus,
rhoncus lacinia lectus enim sit amet nibh. Nullam enim quam,
ultricies et ipsum ut, porttitor laoreet turpis. Quisque eu massa.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur venenatis, sem at laoreet facilisis, sapien nisi tincidunt purus, rhoncus lacinia lectus enim sit amet nibh. Nullam enim quam, ultricies et ipsum ut, porttitor laoreet turpis. Quisque eu massa.
javascript
customElements.
css
body
body.
@
.-wrapper
example-color-switcher
Usage
I keep the javascript in a file called components.js
with the rest of my web components. That gets loaded on the page with:
html
The CSS resides in my base stylesheet.
Another goal is to be able to put this element on the page multiple times and have them all work and stay in sync. I haven't done much work with web components so I'm not sure what the possible approaches are, but I'm sure it's possible. I'll look into that at some point
The Auto feature picks up system settings if the browser has access to them. If you go into your preferences and change them the page will update as well
This approach duplicates each set of styles to line things up for light and dark mode. There are ways to do this without the duplication, but I'm not worried about it. Lots of other things across my site to work on before trying for that micro-optimization