🌓 How to Implement a Dark/Light Mode Toggle Using localStorage in JavaScript
Adding a dark/light mode toggle is a popular feature in modern websites. It improves user experience by letting visitors choose a theme that suits their eyes, especially in low-light environments. In this tutorial, you’ll learn how to add a dark/light mode toggle with a button, and save the user’s preference using localStorage so it stays even after refreshing the page.
✅ What You’ll Learn
-
What is dark/light mode?
-
Why use
localStorage
? -
HTML structure for theme toggle
-
CSS for dark and light themes
-
JavaScript to switch themes and save the choice
-
Step-by-step explanation of the full code
🔹 Step 1: Create the HTML
This is the basic structure with a toggle button.
🧠Explanation:
-
We include a button with
id="toggle-btn"
for switching themes. -
The
<link rel="stylesheet">
includes the external CSS. -
JavaScript is linked at the bottom with
script.js
.
🔹 Step 2: Style the Themes in CSS
We define two themes using CSS: default (light) and .dark-mode
.
🧠Explanation:
-
Default theme is light (
white background
,black text
). -
.dark-mode
class applies dark background and white text. -
Smooth transition is added for visual effect.
🔹 Step 3: JavaScript to Toggle Theme and Use localStorage
Now let’s write the main logic in JavaScript.
🧠Explanation:
-
Get Elements: We access the
body
and thetoggle button
. -
Check localStorage:
-
localStorage.getItem('theme')
checks if the user has a saved theme. -
If it’s
'dark'
, we apply the dark mode by adding.dark-mode
to<body>
.
-
-
Event Listener:
-
When the button is clicked, it toggles the class.
-
Then it saves the theme choice in
localStorage
.
-
📌 What is localStorage and Why Use It?
localStorage
is a browser feature that lets you store data locally that doesn’t get deleted when the page is refreshed.
-
It’s perfect for remembering theme choices.
-
Example: If a user selects dark mode today, it stays even after refreshing or revisiting the site.
🎉 Final Output
When you open the page:
-
It loads the saved theme automatically.
-
You can toggle between dark and light themes.
-
The preference is saved and remembered.
✅ Summary
Step | What You Did |
---|---|
HTML | Created a structure with a toggle button |
CSS | Defined light and dark themes |
JS | Wrote logic to switch themes and save preference |