Theme Toggle System
This pattern uses localStorage as a simple database to remember user preferences across sessions. The data-theme attribute is a CSS-friendly hook that allows all color rules to update simultaneously with a single attribute change.
// Theme initialization and toggle
const theme = localStorage.getItem('theme') || 'light';
document.body.setAttribute('data-theme', theme);
// Toggle button listener (pseudo-code structure)
document.getElementById('theme-toggle').addEventListener('click', function() {
const currentTheme = document.body.getAttribute('data-theme');
const newTheme = currentTheme === 'light' ? 'dark' : 'light';
document.body.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
});
Line-by-line explanation (4 lines)
🔧 Subcomponents:
localStorage.getItem('theme') || 'light'
Retrieves the user's last selected theme from browser storage, defaulting to 'light' if never set
document.body.setAttribute('data-theme', newTheme)
Sets the data-theme attribute which CSS rules use to cascade color changes across the entire page
const theme = localStorage.getItem('theme') || 'light';- Reads the 'theme' value from browser's localStorage, or uses 'light' if it doesn't exist - this survives page reloads
document.body.setAttribute('data-theme', theme);- Sets the data-theme attribute on the body element to 'light' or 'dark', triggering CSS rules that match [data-theme='light'] or [data-theme='dark']
const newTheme = currentTheme === 'light' ? 'dark' : 'light';- Toggles the theme: if currently light, switch to dark; if dark, switch to light
localStorage.setItem('theme', newTheme);- Saves the new theme choice to localStorage so it persists when the user closes and reopens the browser