Designing a Dark Mode Toggle
The user wants to design a dark mode toggle button to switch themes and save preferences using HTML, CSS, and JavaScript. I need to provide a clear, concise code example that includes the full solution: the HTML structure with a button for toggling, CSS for both light and dark themes, and JavaScript that toggles the body class and saves user preferences in localStorage.
I'll structure it simply but effectively, ensuring it's a self-contained snippet!Defining the Toggle Button
I need to refine the CSS for the theme toggle button. The user prefers not to use emojis, so instead of using symbols like 🌙 or ☀︎, I’ll opt for simple text labels like "Dark" and "Light" or icons through inline SVG.
To create a visually appealing toggle, I can design it as a switch slider using .toggle-track and .toggle-thumb elements while including accessible text for "Dark mode." This way, it will still meet accessibility standards!Implementing Theme Preferences in JS
In the JavaScript, on DOMContentLoaded, I need to check for the user's theme preference. I’ll use a storageKey to retrieve preferences from localStorage or detect the system's color scheme with matchMedia. If no preference is found, I’ll default to light mode unless the system prefers dark.
I’ll set up a function to reflect the selected theme by updating the document's attributes and the button's state. Additionally, I’ll add an event listener to handle changes in system theme preferences. I aim to keep it short and include a code snippet with comments for clarity!Crafting the Explanation
I see that the user didn't explicitly ask for an explanation, but I think a brief one would be helpful. I'll structure my answer with a quick overview first: we'll create a toggle button, define two themes using CSS variables, and utilize JavaScript to toggle between them while saving the user's preference in localStorage.
Next, I’ll provide a complete and minimal example in a single HTML file that includes the embedded CSS and JavaScript. I won’t start with phrases like "Great question" — I’ll dive right in!Writing the Code
I’m putting together the code for a dark mode toggle button. This will involve using the data-theme attribute, CSS variables for theme styling, and JavaScript for toggling themes while saving preferences in localStorage. I must remember that aria-pressed reflects the current toggle state. Since emojis are off the table, I'm using textual labels without any icons.
While the user might prefer just the code, I’ll keep explanations minimal and focused! Here is a complete, minimal example of a dark mode toggle that switches themes and remembers the user’s choice with localStorage.
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
<meta charset="UTF-8" />
<title>Dark Mode Toggle</title>
<style>
:root {
--bg: #ffffff;
--text: #111827;
--accent: #2563eb;
--toggle-bg: #e5e7eb;
--toggle-thumb: #ffffff;
}
[data-theme="dark"] {
--bg: #020617;
--text: #e5e7eb;
--accent: #38bdf8;
--toggle-bg: #0f172a;
--toggle-thumb: #e5e7eb;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: var(--bg);
color: var(--text);
transition: background 0.2s ease, color 0.2s ease;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.theme-toggle {
border: none;
background: none;
padding: 0;
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 0.5rem;
font: inherit;
color: inherit;
}
.theme-toggle__label {
font-size: 0.9rem;
}
.theme-toggle__control {
width: 46px;
height: 24px;
border-radius: 999px;
background: var(--toggle-bg);
padding: 3px;
display: flex;
align-items: center;
transition: background 0.2s ease;
}
.theme-toggle__thumb {
width: 18px;
height: 18px;
border-radius: 50%;
background: var(--toggle-thumb);
transform: translateX(0);
transition: transform 0.2s ease, background 0.2s ease;
}
[data-theme="dark"] .theme-toggle__thumb {
transform: translateX(22px);
}
</style>
</head>
<body>
<button
class="theme-toggle"
type="button"
aria-pressed="false"
aria-label="Toggle dark mode"
>
<span class="theme-toggle__label">Dark mode</span>
<span class="theme-toggle__control" aria-hidden="true">
<span class="theme-toggle__thumb"></span>
</span>
</button>
<script>
const storageKey = 'theme-preference';
const toggleBtn = document.querySelector('.theme-toggle');
const getStoredPreference = () => {
const stored = localStorage.getItem(storageKey);
if (stored === 'light' || stored === 'dark') return stored;
// Fallback to system preference
return window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light';
};
const applyTheme = (theme) => {
document.documentElement.setAttribute('data-theme', theme);
toggleBtn.setAttribute('aria-pressed', theme === 'dark');
};
const setTheme = (theme) => {
localStorage.setItem(storageKey, theme);
applyTheme(theme);
};
// Initialize theme on load
applyTheme(getStoredPreference());
// Toggle on click
toggleBtn.addEventListener('click', () => {
const current = document.documentElement.getAttribute('data-theme');
const next = current === 'dark' ? 'light' : 'dark';
setTheme(next);
});
// Optional: update if system theme changes *and* user has no explicit choice
window
.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', (event) => {
const stored = localStorage.getItem(storageKey);
if (stored !== 'light' && stored !== 'dark') {
setTheme(event.matches ? 'dark' : 'light');
}
});
</script>
</body>
</html>
How it works:
- CSS defines light and dark themes using CSS variables on
:root / [data-theme="dark"].
- JavaScript:
- Reads saved preference from
localStorage (or falls back to system theme).
- Sets
data-theme on <html> to light or dark.
- Updates
aria-pressed for accessibility.
- Saves changes back to
localStorage so the choice persists across page loads.