So I have a box .box
. That repeats a spinning animation infinitely.
@keyframes spin {
0% {transform:rotate(0deg);}
100% {transform:rotate(360deg);}
}
The animation is only applied when the box's second class name is running
.box.running {
animation-name:spin;
The purpose of this is so that I can easily stop the animation via javascript. (by removing the second class name.)
I would like it to smoothly transition from wherever it is at in the animation, back to the normal rotation which right now is 0deg
.
Any help would be much appreciated.
I managed to make it work using CSS. The JS allows us to switch class names that's all. You have to use two classes for the animation: one that will make the div spin (.spin
) and the other one that will terminate the spin (.end
).
Both use the same @keyframes
, have the same speed and are linear.
.spin
has a duration of infinite.end
has a duration of 0.5sBasically when the JS script (when button is pressed) the class .end
is added to the div therefore the .spin
's property animation
is overwritten by .ends
's allowing it to rotate the div back to it's original position.
var a = function() {
document.querySelector('.box').setAttribute('class', 'box spin end')
}
document.querySelector('#end').onclick = function() {
a()
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.box {
width: 100px;
height: 100px;
background-color: purple;
animation-fill-mode: backwards;
}
.spin {
animation: spin 2s infinite linear;
}
.end {
animation: spin 2s 0.5s linear;
}
<div class="box spin"></div>
<br>
<button id="end">STOP SPIN</button>
Also don't forget to set the property animation-fill-mode
of .box
to backwards
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With