// Set theme on load. function init() { // Default to light theme. let theme = 'light' // Check media query prefer and set it as dark. if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) { theme = 'dark'; } // Add event handler so if they change media query it'll update. overkill? yes. window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => { let theme = event.matches ? "dark" : "light"; applyTheme(theme); }); // If they have manually changed it use that theme instead. theme = localStorage.getItem("theme") ?? theme // Set it on body. document.body.dataset.theme = theme; // If dark-mode was toggle above we need to fix the icon. let toggle = document.getElementsByName("dark-mode-toggle")[0]; // if it's already dark check it. toggle.checked = theme === 'dark'; applyTheme(theme); } // Toggle the theme. function darkLight() { // Get current theme. let element = document.body; // Invert it. switch (element.dataset.theme) { case "light": element.dataset.theme = "dark"; break; case "dark": element.dataset.theme = "light"; break; } localStorage.setItem("theme", element.dataset.theme); applyTheme(element.dataset.theme); } // Apply theme function applyTheme(theme) { let primaryElements // Find elements and update class. switch (theme) { case 'dark': primaryElements = Array.from(document.querySelectorAll('.is-primary-invert')); primaryElements.forEach((element) => { element.classList.remove('is-primary-invert'); element.classList.add('is-primary'); }); break; case 'light': primaryElements = Array.from(document.querySelectorAll('.is-primary')); primaryElements.forEach((element) => { element.classList.remove('is-primary'); element.classList.add('is-primary-invert'); }); break; } }