Dark Mode
I finally found some time to complete the site’s dark mode feature. As someone who uses dark mode a lot, I couldn’t put the feature off any longer. In theory, adding a dark mode feature is not complicated. However, it can be challenging in practice when integrating the feature into someone else’s code.
The first thing is to set up a button, which is the simplest step. It enables the visitor to toggle the site’s dark mode on & off.
<button
id="dark-mode-toggle"
class="dark-mode-toggle"
aria-label="toggle dark mode"
>
<svg width="100%" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 496 496">
<path
fill="currentColor"
d="M8,256C8,393,119,504,256,504S504,393,504,256,393,8,256,8,8,119,8,256ZM256,440V72a184,184,0,0,1,0,368Z"
transform="translate(-8 -8)"
/>
</svg>
</button>
The next thing is to set up a script to listen for the user’s action and to save their preference locally with ‘localStorage’.
document.addEventListener("DOMContentLoaded", () => {
let darkMode = localStorage.getItem("darkMode");
const darkModeToggle = document.querySelector("#dark-mode-toggle");
const enableDarkMode = () => {
// add class dark mode to the body
document.body.classList.add("darkmode");
// update dark mode in the local storage
localStorage.setItem("darkMode", "enabled");
};
const disableDarkMode = () => {
// remove class dark mode from the body
document.body.classList.remove("darkmode");
// update dark mode in the local storage
localStorage.setItem("darkMode", "disabled");
};
if (darkMode === "enabled") {
enableDarkMode();
}
darkModeToggle.addEventListener("click", () => {
darkMode = localStorage.getItem("darkMode");
if (darkMode !== "enabled") {
enableDarkMode();
console.log("Dark mode enabled");
} else {
disableDarkMode();
console.log("Dark mode disabled");
}
});
// set the initial state based on local storage
if (darkMode === "enabled") {
enableDarkMode();
}
});
This logic will ultimately toggle the CSS dark mode in the site’s <body> element, which can be configured on a separate stylesheet. There are some suggested color themes for dark mode online that I found useful as a starting point in deciding the dark mode theme color palette.