Skip to content

Instantly share code, notes, and snippets.

@remyhunt
Created March 28, 2022 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save remyhunt/d39f43f52d42dac0efe11479dd64f834 to your computer and use it in GitHub Desktop.
Save remyhunt/d39f43f52d42dac0efe11479dd64f834 to your computer and use it in GitHub Desktop.
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