Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run css animation back and forth on clicks

With css @keyframes I'm trying to attach some animation to an element when it is clicked.

.animate {
    animation-name: action;
    animation-duration: 2s;
    animation-timing-function: linear;
    background-color: green;
} 

@keyframes action {
    0% {
        background-color: gray; 
    }  

   50% {
       background-color: red;
   }

   100% {
       background-color: green;
   }
}

DEMO

The .animate class is added on click, and the box animates from gray to green. But now I would like to animate back to gray when I click it again (toggle functionality). I tried using the same animation using animation-direction: reverse but no animation was played. The animation should not play initially (I encountered that a couple of times). Any suggestion how I can achieve that?

like image 349
Jeanluca Scaljeri Avatar asked Mar 30 '18 13:03

Jeanluca Scaljeri


People also ask

How do I trigger an animation again in CSS?

The key to restarting a CSS animation is to set the animation-name of an animation to 'none' and then setting it back to the original animation. As you can see this requires two steps. One to switch it to a different animation and one to set it back.

Which CSS property is used to play animation again and again?

The animation-play-state CSS property sets whether an animation is running or paused.

How do I make a click animation?

Go to Animations > Advanced Animation > Add Animation and select the animation you want to add. Next, go to Animations > Advanced Animation > Animation Pane. In the Animation Pane, select the animated shape or other object that you want to trigger to play when you click it.


1 Answers

I would consider using the animation-play-state property and also use infinite and alternate. The idea is to run the animation and stop it when it ends, then run it again and so on:

const div = document.querySelector('.target')
div.addEventListener('click', (e) => {
   div.classList.add('play');
   setTimeout(function() {
      div.classList.remove('play');
   },2000)
})
.target {
  width: 100px;
  height: 100px;
  background-color: gray;
  cursor: pointer;
  animation: action 2s linear alternate infinite;
  animation-play-state:paused;
}
.play {
  animation-play-state:running;
}

@keyframes action {
  0% {
    background-color: gray; 
  }  

  50% {
    background-color: red;
  }

  100% {
     background-color: green;
  }
}
<div class="target">

</div>
like image 67
Temani Afif Avatar answered Oct 29 '22 09:10

Temani Afif