Search code examples
javascriptcssanimationresultsetsolver

How to reanimate in javascript on click?


I have created animation using keyframes in css, how can re use that animation onclick? I have to change background of the header on click, like carousel, and header must be animated on every click. But it is not working. I set header.style.animation to null and rewrite header.style.animation = 'animate-bg 1s linear' in each click, still not working


Solution

  • Let's add your animation to a class, you can trigger the animation just by removing and adding the class again. This solution uses setTimout to be sure that the browser renders the deletion.

    document.getElementById("header").addEventListener("click", function(e){
      e.target.classList.remove("anim");
      setTimeout(function(){
        e.target.classList.add("anim");
      });
    })
    @keyframes animate-bg {
      0%   {background-color: red;}
      25%  {background-color: yellow;}
      50%  {background-color: blue;}
      100% {background-color: green;}
    }
    
    .anim {
     animation: animate-bg 2s linear;
    }
    <div id="header">Hello Header</div>