I've been working on a unique animation to switch my website between dark and light mode. The animation is quite complex, so I anticipate that the solution will be equally intricate.
Currently, I am toggling between classes, but this approach makes it difficult for me to reverse the animation when switching the button. I have searched for simple solutions online, but unfortunately, I haven't come across any that provide a clear explanation on how to reverse the animation with multiple CSS keyframes.
Below is the CSS section of the code, which is essentially repeated 8 times:
.line {
width: 1rem;
height: 2rem;
background-color: black;
position: absolute;
display: block;
transform: translateY(5rem);
border-radius: 0.5em;
}
.is-dark {
animation: is-dark 2s forwards;
}
@keyframes is-dark {
0% {
height: 2rem;
width: 1rem;
border-radius: 0.5em;
transform: translateX(0) translateY(5rem);
}
33.33% {
height: 1rem;
width: 1rem;
border-radius: 50%;
transform: translateX(0) translateY(5rem);
}
66.66% {
height: 3rem;
width: 3rem;
border-radius: 50%;
transform: translateX(0) translateY(0);
}
100% {
height: 3rem;
width: 3rem;
border-radius: 50%;
transform: translateX(1rem) translateY(-1rem);
}
}
JS
let line = document.querySelector(".line");
let btn = document.querySelector(".btn");
btn.addEventListener("click", toggleDarkMode);
function toggleDarkMode() {
line.classList.toggle("is-dark");
}
For the complete version of this button, you can visit: https://jsfiddle.net/a6euokxy/4/
Thank you in advance, Luk Ramon