I want to create simple text animation. When i click a button, text shifts from fully transparent to fully visible and reverts to transparent. I wrote code that does the animation but only once. The animation doesn’t work anymore every time when i click the button:
JavaScript
x
4
1
function animation() {
2
$("span").removeClass("opacity-effect");
3
$("span").addClass("opacity-effect");
4
}
JavaScript
1
23
23
1
span{
2
opacity: 0;
3
}
4
5
.opacity-effect {
6
animation-name: animate-opacity-effect;
7
animation-duration: 1400ms;
8
animation-fill-mode: forwards;
9
opacity: 0;
10
11
}
12
13
@keyframes animate-opacity-effect {
14
0% {
15
opacity: 0;
16
}
17
50% {
18
opacity: 1;
19
}
20
100% {
21
opacity: 0;
22
}
23
}
JavaScript
1
5
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<span>Hello World!</span>
3
<button onClick="animation()">
4
Start animation
5
</button>
Advertisement
Answer
The animation does not repeat, because for animation to start CSS requires a frame when there was no class.
So, to solve this, you should delay adding class to the next frame
JavaScript
1
7
1
function animation() {
2
$("span").removeClass("opacity-effect");
3
requestAnimationFrame(()=>{
4
$("span").addClass("opacity-effect");
5
});
6
}
7