A few days back I was basically redesigning the long lost todo app from my repositories and I ended up liking my selected color scheme and the dark variant of it. This lead to a simple dark and light toggle that I wrote in about 20 lines of JS, by simply changing a key in the local storage and handling that change and edge case accordingly.
10 mins after this, I realised the the commitlog-web could take advantage of the new color scheme and the web version of it is written in golang and html templates so I needed something vanilla so I just ended up using the above code from the todo implementation. At this point, it's all good, but then a small issue. It'd take the stored theme instead of the system preferred theme only and for someone who's theme changes automatically over the course of the day , this was a problem.
Now most people would be fine with just the prefers-color-scheme
media query
but now I don't assume what scheme the user would want to use for my particular
app so I want him to be able to choose between system, light, dark and now this
is where themer
got created.
It's like 200 lines and you can probably understand by reading the source code , but I'll get through the algorithm just in case.
Also, you can just install themer and use it if you'd find that easier but here goes.
Requirements
The Plan
Code Flow
Date
So, first piece of code.
function Themer() {}
function Themer(config) {
let element = config.trigger
if (element) {
// Check if the trigger was passed a class string or an id string and convert it to a proper html node ref
if (typeof config.trigger === 'string')
element = document.querySelector(config.trigger)
}
// existing state for the theme , fallback to system if nothing is found
const defaultState = localStorage.getItem('theme') || 'system'
}
body
tag to have an
attribute called data-dark-mode
and if this is present, your css
can
over-ride the default light mode variables or you can write custom css with
this as a selector.body[data-dark-mode] button {
background: white;
color: #121212;
}
though, just resetting the variables would be easier, you can find an example here
system
No use posting the snippet cause that's the whole index.js which you can read.
Hope you liked the post,
Adios!