Skip to content

Instantly share code, notes, and snippets.

@remyhunt
Created Mar 28, 2022
Embed
What would you like to do?
vanilla darkmode for my personal site.
const toggle = document.getElementById("toggle");
const html = document.getElementsByTagName("html")[0];
const noti = document.getElementById("darkmode-notification");
const today = new Date();
const hours = today.getHours();
const textLight = "#777";
const textDark = "#aaa";
const detected = ["", ": matched to system UI preference.", ": set by browser local time."];
const setNoti = (note, isDark) => {
isDark ? (noti.style.color = textLight) : (noti.style.color = textDark);
noti.style.opacity = "1";
noti.innerHTML = `dark mode ${isDark ? "on" : "off"}` + note;
setTimeout(() => {
noti.style.opacity = "0";
}, 3000);
};
const setDarkMode = (isDark, transition, note) => {
if (isDark == true) {
setNoti(note, isDark);
toggle.checked = true;
html.classList.add("darkmode");
if (transition) {
html.classList.add("darkmode-transition");
html.classList.remove("lightmode-transition");
}
sessionStorage.setItem("isDarkMode", "true");
} else {
toggle.checked = false;
setNoti(note, isDark);
sessionStorage.setItem("isDarkMode", "false");
if (transition) {
html.classList.add("lightmode-transition");
html.classList.remove("darkmode-transition");
}
html.classList.remove("darkmode");
}
};
// checks session -> then system preferences -> sunset time
if (sessionStorage.getItem("isDarkMode") != null) {
if (sessionStorage.getItem("isDarkMode") == "true") {
setDarkMode(true, true, detected[0]);
} else {
setDarkMode(false, true, detected[0]);
}
} else {
setTimeout(() => {
if (window.matchMedia) {
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
setDarkMode(true, true, detected[1]);
} else {
setDarkMode(false, true, detected[1]);
}
} else {
if (hours > 20 || hours < 8) {
setDarkMode(true, true, detected[2]);
} else {
setDarkMode(false, true, detected[2]);
}
}
}, 800);
}
// Listener for a change in checkbox
toggle.addEventListener("change", (e) => {
e.target.checked ? setDarkMode(true, true, "") : setDarkMode(false, true, "");
});
// Listener for a change in Media Query (from system UI)
window.matchMedia("(prefers-color-scheme: dark)").addListener((e) => {
e.matches ? setDarkMode(true, true, detected[1]) : setDarkMode(false, true, detected[1]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment