Learn how to create a simple day and night toggle button with icon using HTML, CSS, and JavaScript. In this step-by-step tutorial, we'll walk through the process of building a responsive toggle button that changes the background color and icon color based on the day and night mode. Customize the colors and styles to match your design preferences.
đđ Explore the code and follow along to enhance your front-end development skills!
HTML (index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Day and Night Toggle Button</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h2>Day and Night button with icon</h2>
<div class="toggle-container">
<div id="toggle-icon" class="sun-icon">â ☀</div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS (styles.css):
.toggle-container {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
.sun-icon {
cursor: pointer;
}
JavaScript (script.js):
const toggleIcon = document.getElementById("toggle-icon");
let isDayMode = true;
toggleIcon.addEventListener("click", () => {
isDayMode = !isDayMode;
document.body.style.backgroundColor = isDayMode ? '#f0f0f0' : '#333';
if (!isDayMode) {
document.body.style.color = "white"; // Change color code here
toggleIcon.style.color = "#fff"; // Change color code for the icon
} else {
document.body.style.color = ""; // Reset to default color
toggleIcon.style.color = "";
}
toggleIcon.textContent = isDayMode ? '\u2600' : '\u263E'; // Unicode characters for sun and moon icons
});
Note : Feel free to copy and paste each section into separate files (index.html, styles.css, script.js) and run the HTML file in your browser to see the day and night toggle button in action.
I'm a dedicated full-stack developer, entrepreneur, and the proud owner of ocec.org.in , hailing from the vibrant country of India. My passion lies in creating informative tutorials and sharing valuable tips that empower fellow artisans in their journey. With a deep-rooted love for technology, I've been an ardent enthusiast of PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, Codeigniter, and Bootstrap from their earliest days. My philosophy revolves around the values of hard work and unwavering consistency, driving me to continuously explore, create, and share my knowledge with the tech community.
helllo