Back to Tutorials
Web Development
15 min read
Sahasransu Satpathy
2/1/2026
Dark Mode Toggle in JavaScript
Learn how to implement a dark mode toggle for your website using JavaScript and CSS
Introduction
Dark mode improves user experience by reducing eye strain and giving your website a modern look. This tutorial shows how to implement a dark/light mode toggle using JavaScript and CSS.
Step 1: HTML Structure
Create a button for toggling dark mode:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dark Mode Toggle</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button id="darkModeToggle">Toggle Dark Mode</button>
<h1>Welcome to Dark Mode Tutorial</h1>
<p>This is a simple example of dark mode using JavaScript.</p>
<script src="script.js"></script>
</body>
</html>
Step 2: CSS Styling
Define styles for light and dark modes:
body {
background-color: #ffffff;
color: #000000;
font-family: Arial, sans-serif;
text-align: center;
transition: background-color 0.3s, color 0.3s;
padding: 50px;
}
body.dark-mode {
background-color: #121212;
color: #ffffff;
}
button {
padding: 10px 20px;
margin-bottom: 20px;
cursor: pointer;
font-size: 16px;
}
Step 3: JavaScript Toggle Function
Add functionality to switch between light and dark modes:
const toggleButton = document.getElementById('darkModeToggle');
const body = document.body;
toggleButton.addEventListener('click', () => {
body.classList.toggle('dark-mode');
});
Step 4: Optional – Save Preference
You can store the user’s preference in localStorage:
// Check saved mode on load
if(localStorage.getItem('dark-mode') === 'enabled') {
body.classList.add('dark-mode');
}
// Toggle and save preference
toggleButton.addEventListener('click', () => {
body.classList.toggle('dark-mode');
if(body.classList.contains('dark-mode')) {
localStorage.setItem('dark-mode', 'enabled');
} else {
localStorage.setItem('dark-mode', 'disabled');
}
});
Step 5: Testing
- Open your HTML file in a browser.
- Click the toggle button to switch between light and dark modes.
- Reload the page to confirm the preference is saved.
Conclusion
You now have a fully functional dark mode toggle for your website. Customize colors, fonts, and transitions to match your design.
SEO Suggestions:
- Main keywords: dark mode toggle, JavaScript dark mode, website dark mode tutorial, dark/light theme toggle
- Meta description: Implement a dark mode toggle on your website using JavaScript and CSS. Step-by-step beginner-friendly guide.
- Catchy title suggestions: "Dark Mode Toggle in JavaScript – Step-by-Step Guide", "Add Dark Mode to Your Website Easily"
Previous Tutorial
Browse All TutorialsNext Tutorial
Browse All Tutorials