Here is a simple pulsating animation using CSS keyframes.
The problem is if I want to discard or remove the animation in the middle of it, the animation stops with a jerking movement (a sudden jump to its initial state as you can see in the snippet).
I want the animation to go back to its initial state smoothly even if you stop it in the middle of the animation.
JQuery and TweenMax are accepted.
Is there any way to do that?
let test = document.getElementById("test");
setTimeout(function(){
test.classList.add("addAniamte");
}, 2000)
setTimeout(function(){
test.classList.remove("addAniamte");
test.classList.add("removeAniamte");
console.log('stoping aniamtion!');
}, 4500)
@-webkit-keyframes pulse {
0% {
-webkit-transform: scale(1, 1);
}
50% {
-webkit-transform: scale(3, 3);
}
100% {
-webkit-transform: scale(1, 1);
};
}
#test {
background: red;
width: 20px;
height: 20px;
margin: 60px;
}
.addAniamte{
-webkit-animation: pulse 1s linear infinite;
animation: pulse 1s linear infinite;
}
.removeAniamte{
-webkit-animation: none;
animation:none;
}
<div id="test"></div>
This is quite easy to do with GSAP! Here's how to do something like this in GSAP 3.
var tween = gsap.from("#test", {duration: 1, scale: 0.33, repeat: -1, yoyo: true, paused: true});
function startAnimation() {
tween.play();
}
function stopAnimation() {
tween.pause();
gsap.to(tween, {duration: 0.5, progress: 0});
}
#test {
background: red;
width: 60px;
height: 60px;
margin: 60px;
}
<div id="test"></div>
<button onclick="startAnimation()">Start</button>
<button onclick="stopAnimation()">Stop</button>
<script src="https://cdn.jsdelivr.net/npm/gsap@3.0.4/dist/gsap.min.js"></script>
Without GSAP (or at least a JS-only approach), it's incredibly messy and error prone as the other answer shows. In fact, I had my own question which lead to a CSS-Tricks article on the subject.