Reputation: 135
I have a element which has an infinite animation
animation: start .75s steps(19) infinite;
Now after a some time (this time changes) I would like to stop the animation but so that it smoothly runs out. When I stop the animation via jQuery by removing the animation class it just stops.
I hope you have a idea for this?
Upvotes: 2
Views: 1746
Reputation: 93
Actually, there is a much simpler way using Svelte. Say loading
is a boolean. The animation should run, when loading
is true. Then we have e.g. a SVG line
that should jump up and down.
<line id="line-0" class="{animateClass ? 'animate' : ''}" x1="0" y1="0" x2="0" y2="20"/>
We add the following CSS.
line {
stroke: black;
stroke-width: 3px;
transition: all 0.8s ease-in-out;
}
line.animate {
animation-direction: alternate;
transition: all 0.8s ease-in-out;
transform: translateY(-50%);
}
As you can see, we use single-run transitions. A jump-up transition when the animate
class is there and a fall-down transition, when the animate
class is gone.
Now, we need some JavaScript to control for the ups and downs.
let animateClass = false;
let intervalId;
function animateLine(loading) {
if (loading) {
if (!intervalId) {
animateClass = true;
intervalId = setInterval(() => animateClass = !animateClass, 800);
}
} else {
clearInterval(intervalId);
intervalId = null;
animateClass = false;
}
}
$: animateLine(loading); // call the function every time loading is updated
Each time loading
changes, the animateLine
function is called and alternates between jump-up and fall-down transitions. This also guarantees a smooth stop of the animation. Moreover, the animation itself is pure CSS and thus very performant.
Please note that the setInterval
function handles the callback execution every 800 ms. This is exactly the length of the CSS transitions.
Of course, you can implement this with Vanilla JS, too. However, Svelte delivers some syntactic sugar for reactivity.
See also this blog post.
Upvotes: 2
Reputation: 11
Try using a this very simple Javascript syntax:
function stopAnimation(){
document.getElementById('animationElement').setAttribute('class', 'displayNone');
};
setTimeout(stopAnimation, 5000);
the id we're targeting is the one which does the animation and we're giving it a class named 'displayNone' which is in our CSS file.after this we call the the function doing all this after 5 seconds which is when your animation ends. you can change this to whatever time you want your animation to end.
and add this to your CSS:
.displayNone{
display: none;
}
N.B: make sure to add the css code BEFORE the animation properties or else it wont work
Upvotes: 0