Save theme choice
Part of the JavaScript in Action section of Coddy's HTML journey — lesson 17 of 27.
When users switch between light and dark themes, we want the website to remember their choice.
For this, we use <strong>localStorage</strong> in JavaScript. It stores data in the browser, and this data stays even after the page is refreshed or the browser is closed.
The logic is:
- When the user toggles the theme, save the current theme into
localStorage. - When the page loads, check
localStorageand apply the saved theme automatically.
HTML:
<button id="themeToggle">Toggle Theme</button>
CSS:
body.dark-mode {
background-color: #222;
color: #fff;
}This code checks if the user previously saved a dark theme in localStorage and applies it when the page loads.
When the button is clicked, it toggles dark mode on the page and then updates localStorage so the preference is remembered for the next visit
const button = document.getElementById("themeToggle");
// Apply saved theme on page load
if (localStorage.getItem("theme") === "dark") {
document.body.classList.add("dark-mode");
}
button.addEventListener("click", function () {
document.body.classList.toggle("dark-mode");
// Save preference
if (document.body.classList.contains("dark-mode")) {
localStorage.setItem("theme", "dark");
} else {
localStorage.setItem("theme", "light");
}
});This ensures the user's preference is maintained across visits to your site.
Challenge
EasyCreate a theme toggle that remembers user preference.
Steps:
- On page load: Check if the user previously selected dark mode
- If "dark" is saved in localStorage, add the "dark-mode" class to the body
- When toggle button is clicked: Switch between light and dark themes
- Toggle the "dark-mode" class on the body element
- Save the current theme in localStorage
Try it yourself
<!DOCTYPE html>
<html>
<head>
<title>Theme Preference Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button id="themeToggle">Toggle Theme</button>
<h1>Saving Theme Preference</h1>
<p>
Try switching between light and dark mode using the button above.
Refresh the page — your choice is remembered thanks to <strong>localStorage</strong>.
</p>
<script src="script.js"></script>
</body>
</html>
This lesson includes a short quiz. Start the lesson to answer it and track your progress.