--- title: Dark Mode Toggle description: Dark mode without the flash of default theme date: 2021-04-21 draft: false slug: /pensieve/dark-mode-toggle tags: - Theming - Dark Mode --- Dark mode toggle without the flash of default theme. Important bits: - CSS variables for color theming - Put `data-theme` attribute on ``, not ``, so we can run the JS before the DOM finishes rendering - Run local storage check in the `` - JS for toggle button click handler can come after render ## HTML ```html ...
``` ## CSS Variables ```css :root { --bg: #ffffff; --text: #000000; } [data-theme='dark'] { --bg: #000000; --text: #ffffff; } ``` ## JavaScript ```js:title=app.js const themeToggleBtn = document.querySelector('.js-theme-toggle'); themeToggleBtn.addEventListener('click', () => onToggleClick()); const onToggleClick = () => { const { theme } = document.documentElement.dataset; const themeTo = theme && theme === 'light' ? 'dark' : 'light'; const label = `Activate ${theme} mode`; document.documentElement.setAttribute('data-theme', themeTo); localStorage.setItem('theme', themeTo); themeToggleBtn.setAttribute('aria-label', label); themeToggleBtn.setAttribute('title', label); }; ``` ## Resources - - - - -