Day and Night Toggle Button with Icon | HTML, CSS, JavaScript Tutorial

Day and Night Toggle Button with Icon | HTML, CSS, JavaScript Tutorial

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!

Below is the code separated into three sections: HTML, CSS, and JavaScript.

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">☀ &#9728;</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.
 

 


Share this article







Related Posts




0 Comments



Load more Comments

Post a Comment


helllo
Ocec Copyright text of dont't copyright our content