Here’s a simple way to create a toggle button to switch between light mode and dark mode using HTML, CSS and JavaScript function.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>Document</title>
</head>
<body>
<div class="container">
<h1>Click to switch between Light Mode and Dark Mode</h1>
<button id="toggle">Click Here</button>
</div>
<script src="app.js"></script>
</body>
</html>
body {
background-color: #fff;
color: #333;
transition: background-color 0.5s ease-in;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
}
.dark-mode {
background-color: #333;
color: #f5f5f5;
}
In the above CSS code block, we’ve created the default light mode background for the body. We’ve also created another dark-mode class which will be activated dynamically using the JavaScript function.
const toggleBtn = document.getElementById("toggle");
const body = document.body;
toggleBtn.addEventListener("click", function () {
body.classList.toggle("dark-mode");
});
In the above JavaScript section, we’ve written a JS function to toggle the button on click event to dark-mode class in the CSS section.
Note that the .dark-mode class is not already present inside the HTML section of the code. It’s added in the CSS section and activated using a simple JavaScript event listener.