Persistence & Application Preferences
20 min read
Persist the Theme Preference
Task
Store the user’s selected theme in localStorage.
Open
Open:
js/ui.js
Create a theme storage key:
const THEME_KEY = 'calculator-theme';
When the theme changes, save it:
function saveTheme(theme) {
localStorage.setItem(THEME_KEY, theme);
}
Then load the saved theme at startup:
function loadTheme() {
return localStorage.getItem(THEME_KEY) || 'dark';
}
Apply the value using the theme mechanism already prepared by the starter:
const theme = loadTheme();
document.documentElement.dataset.theme = theme;
When the theme toggle changes the theme, call:
saveTheme(nextTheme);
Use the existing theme classes, attributes, or toggle logic from the starter rather than changing the CSS.
Test
- Switch between light and dark mode.
- Refresh the page.
- Confirm the selected theme remains active.
- Clear the site’s local storage and confirm the application falls back to its default theme.
Checkpoint
Both calculation history and the user’s theme preference now survive a page refresh.