A System Preferences Based Light/Dark Mode Switcher
Head's Up
This is a work in progress. I'm checking with folks for accessibility help and a smoke test.
Introduction
I'm building out an example site for my Neopoligen^neo^^ 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.
Goals
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. (I'm reaching out to some accessibility folks to see what else I need to do to make sure it's as accessible as possible)
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
:;
:;
:;
:;
}
:;
:;
:;
:;
}
{
:;
:;
:;
:;
}
:;
:;
:;
:;
}
}
:;
:;
}
:;
:;
}
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:
Code
The CSS resides in my base stylesheet.
Notes
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
Footnotes
-
(id:neo)the website building app I'm working on