mirror of
https://github.com/davegallant/davegallant.github.io.git
synced 2025-08-07 00:58:13 +00:00
Only save theme when toggle is done
This commit is contained in:
@@ -3,6 +3,10 @@ function getTheme() {
|
|||||||
// User preference
|
// User preference
|
||||||
return localStorage.getItem("theme");
|
return localStorage.getItem("theme");
|
||||||
}
|
}
|
||||||
|
// Undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
function getOSTheme() {
|
||||||
if (window.matchMedia) {
|
if (window.matchMedia) {
|
||||||
// OS preference
|
// OS preference
|
||||||
return window.matchMedia("(prefers-color-scheme: light)").matches
|
return window.matchMedia("(prefers-color-scheme: light)").matches
|
||||||
@@ -21,20 +25,28 @@ function setTheme(theme) {
|
|||||||
const prismLight = document.getElementById("prism-light");
|
const prismLight = document.getElementById("prism-light");
|
||||||
prismDark.toggleAttribute("disabled", theme === "light");
|
prismDark.toggleAttribute("disabled", theme === "light");
|
||||||
prismLight.toggleAttribute("disabled", theme === "dark");
|
prismLight.toggleAttribute("disabled", theme === "dark");
|
||||||
|
}
|
||||||
|
|
||||||
// Store user preference
|
function saveTheme(theme) {
|
||||||
localStorage.setItem("theme", theme);
|
localStorage.setItem("theme", theme);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Initial load
|
// Initial load
|
||||||
const theme = getTheme();
|
const theme = getTheme();
|
||||||
if (theme) setTheme(theme);
|
const osTheme = getOSTheme();
|
||||||
|
if (theme) {
|
||||||
|
setTheme(theme);
|
||||||
|
// Store user preference
|
||||||
|
} else if (osTheme) {
|
||||||
|
setTheme(osTheme);
|
||||||
|
}
|
||||||
|
|
||||||
function toggleTheme(e) {
|
function toggleTheme(e) {
|
||||||
const theme = e.currentTarget.classList.contains("light--hidden")
|
const theme = e.currentTarget.classList.contains("light--hidden")
|
||||||
? "light"
|
? "light"
|
||||||
: "dark";
|
: "dark";
|
||||||
setTheme(theme);
|
setTheme(theme);
|
||||||
|
saveTheme(theme);
|
||||||
}
|
}
|
||||||
|
|
||||||
// This script is inlined in the <head> of the document, so we have to wait
|
// This script is inlined in the <head> of the document, so we have to wait
|
||||||
|
Reference in New Issue
Block a user