JSFiddle - React, Tailwind, and code Playground
by davidxmartins
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sun-Moon Toggle</title>
<style>
body {
background-color: #fff;
transition: background 0.5s ease-in-out;
}
.theme-toggle {
width: 50px;
height: 50px;
background: none;
border: none;
cursor: pointer;
outline: none;
display: flex;
align-items: center;
justify-content: center;
}
svg {
width: 50px;
height: 50px;
fill: #d89000;
transition: transform 0.7s ease-in-out;
}
</style>
</head>
<body>
<button class="theme-toggle" aria-label="Toggle theme">
<svg id="theme-icon" viewBox="0 0 30 30">
<!-- Sun (Default) -->
<g id="sun">
<circle cx="15" cy="15" r="6.92"></circle>
<circle cx="15" cy="2.59" r="2.59"></circle>
<circle cx="15" cy="27.35" r="2.59"></circle>
<circle cx="27.35" cy="15" r="2.59"></circle>
<circle cx="2.59" cy="15" r="2.59"></circle>
<circle cx="23.72" cy="6.22" r="2.59"></circle>
<circle cx="6.22" cy="23.72" r="2.59"></circle>
<circle cx="23.72" cy="23.72" r="2.59"></circle>
<circle cx="6.22" cy="6.22" r="2.59"></circle>
</g>
</svg>
</button>
<script>
const button = document.querySelector(".theme-toggle");
const svg = document.querySelector("#theme-icon");
let isDark = false;
button.addEventListener("click", () => {
isDark = !isDark;
document.body.style.backgroundColor = isDark ? "#1a1a1a" : "#fff";
// Rotate the icon
svg.style.transform = "rotate(360deg)";
// Switch between Sun and Moon after the rotation completes
setTimeout(() => {
...