sansSpoon
sansSpoon

Reputation: 2185

CSS - transition animation on class add/remove

I'm trying to set a transition to a transform that is applied as part of a animation. In this codepen example and inline here, I'm adding a class to start/stop the animation keyframes. When the button is clicked to stop the rotation, it snaps back to the start frame.

Is it possible to have it either complete the rotation or smoothly roll back to it's start state?

var toggle2d = document.getElementById('toggle-2d');
var plain = document.querySelector('.plain');


toggle2d.onclick = () => {
 plain.classList.toggle('animate-2d');
}
.plain {
  top: 50%;
  left: 50%;
  display: flex;
	align-items: center;
	justify-content: center;
  position: absolute;
}

.orbit {
  width: 200px;
  height: 200px;
  border: 1px solid black;
  border-radius: 50%;

  display: flex;
  align-items: center;
  justify-content: flex-end;

  position: absolute;

  transform-style: preserve-3d;

  transition: all 1s linear;
}

.body {
  width: 30px;
  height: 30px;
  background-color: brown;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transform-style: preserve-3d;
}

.animate-2d .orbit {
  transition: all 1s linear;
  animation: orbit-cw infinite linear;
  animation-duration: 5s;
  animation-fill-mode: both;
}

@keyframes orbit-cw {
  100% {
    transform: rotateZ(360deg);
  }
}
<button type="button" id="toggle-2d">toggle 2d</button>
<div class="plain">
  <div class="orbit">
    <div class="body">
    </div>
  </div>
</div>

Upvotes: 1

Views: 1436

Answers (1)

GSSwain
GSSwain

Reputation: 6133

You can use the animationiteration event to achieve this.

var stopRequested = false;

toggle2d.onclick = () => {
    stopRequested = !stopRequested;
    if(!stopRequested) {
        plain.classList.add('animate-2d');
    }
}

plain.addEventListener("animationiteration", function(){
    if(stopRequested){
        plain.classList.remove('animate-2d');
    }
});

Upvotes: 1

Related Questions