I'm working on a little animation for toggling my website between dark- and light mode. It's a pretty complicated animation, so I'm guessing the solution will be complicated as well.
I basically toggle between classes, but this prevents me from being able to reverse the animation when toggling the button. Been looking for simple solutions around the web, but didn't find any that explains how to reverse the animation with multiple CSS keyframes.
Here's the CSS part of the code which is basically 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");
}
Here's the complete version of this button: https://jsfiddle.net/a6euokxy/4/
Thanks in advance, Luk Ramon