Here, I am implementing a dark mode as Windows and iOS have all introduced dark modes. This will automatically identify systems that are set to dark modes, and apply the enclosed CSS rules. However; even though users may have their system set to dark mode, it may be the case that they prefer the light or default theme of a specific website. Here, JavaScript is used to identify which theme the user has set, or if they have over-ridden their OS theme, as well as to toggle between the two, this is included in the header prior to the output of the html <body>….</body> . For the best user experience, I want to ensure that these users can toggle between dark and default modes for those cases.
CSS rule:
@media (prefers-color-scheme: dark) {body {
color:#fff;
background:#333333
}
Js code :
// Function to create the links to the light and dark external CSS files
function loadTheme(theme) {
const id = Math.floor(1000 + Math.random() * 9000); //To generate a random 4 digit number
const link = document.querySelector("link");
link.href = `${theme}.css?id=${id}`; //Add the ID so the CSS file is unique each load. This prevents browser caching.
}
// Same eventListener but calling loadTheme() with applicable parameter
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", (event) => {
const modeChange = event.matches ? "dark" : "light";
const autoMode = document.querySelector(".selected");
if (autoMode.classList.contains("auto")) {
if (modeChange === "dark") {
loadTheme("dark");
} else {
loadTheme("light");
}
}
});
Note:
If going with above approach, remember to replace all document.body.classList.add(“dark-mode”) with loadTheme() in the other functions too, and create separate light.css and dark.css files.