My personal website vittoriogioda.com
blog portfolio personal-website
at main 75 lines 2.4 kB view raw
1(() => { 2 "use strict"; 3 const LS_THEME_KEY = "theme"; 4 const THEMES = { 5 LIGHT: "light", 6 DARK: "dark", 7 AUTO: "auto", 8 }; 9 10 const body = document.body; 11 const config = body.getAttribute("data-theme"); 12 13 const getThemeState = () => { 14 const lsState = localStorage.getItem(LS_THEME_KEY); 15 if (lsState) return lsState; 16 17 let state; 18 switch (config) { 19 case THEMES.DARK: 20 state = THEMES.DARK; 21 break; 22 case THEMES.LIGHT: 23 state = THEMES.LIGHT; 24 break; 25 case THEMES.AUTO: 26 default: 27 state = window.matchMedia("(prefers-color-scheme: dark)") 28 .matches 29 ? THEMES.DARK 30 : THEMES.LIGHT; 31 break; 32 } 33 return state; 34 }; 35 36 const initTheme = (state) => { 37 if (state === THEMES.DARK) { 38 document.documentElement.classList.add(THEMES.DARK); 39 document.documentElement.classList.remove(THEMES.LIGHT); 40 } else if (state === THEMES.LIGHT) { 41 document.documentElement.classList.remove(THEMES.DARK); 42 document.documentElement.classList.add(THEMES.LIGHT); 43 } 44 }; 45 46 // init theme ASAP, then do the rest. 47 initTheme(getThemeState()); 48 requestAnimationFrame(() => body.classList.remove("notransition")) 49 const toggleTheme = () => { 50 const state = getThemeState(); 51 if (state === THEMES.DARK) { 52 localStorage.setItem(LS_THEME_KEY, THEMES.LIGHT); 53 initTheme(THEMES.LIGHT); 54 } else if (state === THEMES.LIGHT) { 55 localStorage.setItem(LS_THEME_KEY, THEMES.DARK); 56 initTheme(THEMES.DARK); 57 } 58 }; 59 60 window.addEventListener("DOMContentLoaded", () => { 61 // Theme switch 62 const lamp = document.getElementById("mode"); 63 64 lamp.addEventListener("click", () => toggleTheme()); 65 66 // Blur the content when the menu is open 67 const cbox = document.getElementById("menu-trigger"); 68 69 cbox.addEventListener("change", function () { 70 const area = document.querySelector(".wrapper"); 71 if (this.checked) return area.classList.add("blurry"); 72 area.classList.remove("blurry"); 73 }); 74 }); 75})();