Build a Dark Mode Toggle with JavaScript
Almost every website you use today has a dark mode. It is not just a style choice — users genuinely prefer it at night, and it has become one of those small features people notice when it is missing. The good news is that building one takes about 30 lines of code.
What you are building
A button that switches your page between a light theme and a dark theme, and remembers the choice when the user comes back. That last part matters: a toggle that forgets is worse than no toggle at all.
The CSS: define your themes with variables
:root { --bg: #ffffff; --text: #1a1a1a; } body.dark { --bg: #1a1a1a; --text: #f5f5f5; } body { background: var(--bg); color: var(--text); transition: background 0.3s, color 0.3s; } CSS variables do the heavy lifting. You change one class on the body, and every element using the variables updates at once.
The JavaScript: toggle and remember
const toggleBtn = document.querySelector('#theme-toggle'); // Load the saved choice on page load if (localStorage.getItem('theme') === 'dark') { document.body.classList.add('dark'); } toggleBtn.addEventListener('click', () => { document.body.classList.toggle('dark'); const theme = document.body.classList.contains('dark') ? 'dark' : 'light'; localStorage.setItem('theme', theme); }); Two ideas here. classList.toggle switches the theme, and localStorage saves the choice in the browser so it survives a refresh.
Respect the user's system setting
// If no saved choice, follow the operating system if (!localStorage.getItem('theme')) { const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; if (prefersDark) document.body.classList.add('dark'); } This is the detail that makes your toggle feel professional. Most users have already told their operating system which theme they prefer. Read that first, and only override it when they click your button.
The one thing to remember
Put the theme-loading script as early as possible in your page — ideally before the page paints. Otherwise users see a flash of the light theme before dark mode kicks in, and that flash is the most common dark mode bug on the web.
原文:https://www.a8q9.cn/en/article/build-a-dark-mode-toggle-with-javascript-643c14.html