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:
function animation() { $("span").removeClass("opacity-effect"); $("span").addClass("opacity-effect"); }
span{ opacity: 0; } .opacity-effect { animation-name: animate-opacity-effect; animation-duration: 1400ms; animation-fill-mode: forwards; opacity: 0; } @keyframes animate-opacity-effect { 0% { opacity: 0; } 50% { opacity: 1; } 100% { opacity: 0; } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span>Hello World!</span> <button onClick="animation()"> Start animation </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
function animation() { $("span").removeClass("opacity-effect"); requestAnimationFrame(()=>{ $("span").addClass("opacity-effect"); }); }