I’m trying to make a website but I’m having trouble making a dark/light theme using JS. Does anyone know an easy way to make a dark/light theme?
- My idea is fetching elements with a certain style and changing it’s CSS color property.
I tried using document.getElementsByClassName() but it made too much of a hassle. It’s also really inefficient.
>Solution :
Define your colours using custom properties.
(You will want more colours than this example)
body {
--main-bg-color: yellow;
--main-fg-color: black;
}
Then override them in a dark mode stylesheet:
@media (prefers-color-scheme: dark) {
body {
--main-bg-color: black;
--main-fg-color: yellow;
}
}
Then, if you want the user to be able to toggle with your own UI as well as using their system wide choice, define them again with a class:
body.lightMode {
--main-bg-color: yellow;
--main-fg-color: black;
}
body.darkMode {
--main-bg-color: black;
--main-fg-color: yellow;
}
Then just use those variables when you want color name:
h1 {
color: --main-bg-color;
}
If you want the UI to change the style then:
function eventHandler() {
const b = document.body;
if (b.classList.contains("darkMode")) {
b.classList.remove("darkMode");
b.classList.add("lightMode");
} else {
b.classList.remove("lightMode");
b.classList.add("darkMode");
}
};