How to Add Dark Mode to Your Website with Just 10 Lines of JavaScript
Want to make your website stand out and improve readability for users at night? Dark mode is a modern web feature that not only looks stylish but also reduces eye strain, and it's in high demand. In this beginner-friendly tutorial, I'll show you how to add a fully functional dark mode toggle to any website using just HTML, CSS, and 10 lines of JavaScript. No libraries. No frameworks.
🚀 What You'll Learn
- How to build a dark mode toggle button
- How to switch themes using JavaScript
- How to store user preferences using
localStorage
🧱Step 1: Basic HTML Structure
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dark Mode Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>Welcome to TapCoders</h1>
<p>This website now supports dark mode! 🔥</p>
<button id="toggle">🌙 Toggle Dark Mode</button>
</div>
<script src="script.js"></script>
</body>
</html>
🎨 Step 2: CSS Styling
body {
margin: 0;
padding: 40px;
font-family: Arial, sans-serif;
background: #ffffff;
color: #111;
transition: all 0.3s ease;
}
.dark-mode {
background: #121212;
color: #ffffff;
}
button {
margin-top: 20px;
padding: 10px 20px;
background-color: #222;
color: #fff;
border: none;
border-radius: 8px;
cursor: pointer;
}
button:hover {
background-color: #444;
}
🧠 Step 3: JavaScript in 10 Lines
const toggleBtn = document.getElementById("toggle");
toggleBtn.addEventListener("click", () => {
document.body.classList.toggle("dark-mode");
// Save mode in localStorage
const isDark = document.body.classList.contains("dark-mode");
localStorage.setItem("darkMode", isDark);
});
// Load preference on page load
window.onload = () => {
const savedMode = localStorage.getItem("darkMode") === "true";
if (savedMode) document.body.classList.add("dark-mode");
};
💡 How It Works
We use JavaScript to add or remove a CSS class on the body when the user clicks the toggle. The styles for the .dark-mode
class are predefined in CSS. And to make this preference persistent, we save the choice in localStorage
, so the user's choice sticks after they reload the page.
✅ Final Result
- Dark mode toggle that works smoothly
- Retains user choice across sessions
- Lightweight and fast — no external tools needed
🔁 What’s Next?
If you enjoyed this dark mode tutorial, you’ll love this step-by-step guide: Complete Responsive Personal Portfolio Website — perfect for showcasing your developer skills online.
📢 Share this post
Like this tip? Share it with your developer friends! And don't forget to comment below if you have any questions or need help customizing this dark mode feature.