Adding a Dark Mode toggle feature to your web project can greatly enhance user experience, making it easier on the eyes during nighttime browsing. In this tutorial, we’ll walk through how to create a simple yet visually appealing Dark Mode toggle using HTML, CSS, and JavaScript, with icons representing the on and off states.
Step 1: HTML Structure
Start by setting up the basic HTML structure. You'll need a container for your content and an image-based button to toggle 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="styles.css">
</head>
<body>
<div class="content">
<h1>Dark Mode Toggle</h1>
<button id="darkModeToggle">
<img src="light-mode-icon.png" alt="Light Mode" id="toggleIcon">
</button>
</div>
<script src="script.js"></script>
</body>
</html>
Step 2: CSS Styling
Next, style your content and the Dark Mode feature using CSS. Define the styles for both light and dark modes, and make sure the toggle button is clearly visible:
body {
font-family: Arial, sans-serif;
transition: background-color 0.3s ease, color 0.3s ease;
}
.content {
text-align: center;
margin-top: 20%;
}
button {
background: none;
border: none;
cursor: pointer;
}
.dark-mode {
background-color: #121212;
color: #ffffff;
}
.light-mode {
background-color: #ffffff;
color: #000000;
}
Step 3: JavaScript Functionality
Finally, add JavaScript to make the Dark Mode toggle functional. This script will change the mode based on user interaction and swap the icon accordingly:
const toggleButton = document.getElementById('darkModeToggle');
const toggleIcon = document.getElementById('toggleIcon');
toggleButton.addEventListener('click', () => {
document.body.classList.toggle('dark-mode');
if (document.body.classList.contains('dark-mode')) {
toggleIcon.src = 'dark-mode-icon.png';
} else {
toggleIcon.src = 'light-mode-icon.png';
}
});
This implementation allows you to easily switch between light and dark modes with a simple click, improving your website's usability and giving it a modern touch.
Comments
Post a Comment