Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - Sharing @Keyframes Ruleset with Animation-Direction and Animation-Fill-Mode?

I have a simple blue square that I want to control with 2 buttons, "Move Left" and "Move Right".

  • Move Left: Should move the blue square from the right to the left, fade the opacity from 0.5 to 1 and retain the last frame of the animation.

  • Move Right: Should move the blue square from the left to the right, fade the opacity from 1 to 0.5 and retain the last frame of the animation.

I want to share a single @keyframes move ruleset, but I'm confused with how animation-direction and animation-fill-mode should work together.

The first time the animation is fired is correct, whether the animation moves left or right, but after that it no longer animates as it should.

const square = document.getElementById("square");

const leftButton = document.getElementById("left");
leftButton.addEventListener("click", () => {
    square.classList.remove("moveRight");
    square.classList.add("moveLeft");
});

const rightButton = document.getElementById("right")
rightButton.addEventListener("click", () => {
    square.classList.remove("moveLeft");
    square.classList.add("moveRight");
})
#square {
    width: 200px;
    height: 200px;
    background-color: blue;
    margin-top: 20px;
    position: relative;
}
 
 .moveLeft {
     animation: move 1s linear normal forwards;
 }
 
 .moveRight {
     animation: move 1s linear reverse forwards;
 }
 
 @keyframes move {
     from {left: 100px; opacity: 0.5;}
     to {left: 0; opacity 1;}
 }
<input type="button" id="left" value="MOVE LEFT">
<input type="button" id="right" value="MOVE RIGHT">

<div id="square"></div>
like image 338
Chunky Chunk Avatar asked Oct 30 '22 06:10

Chunky Chunk


1 Answers

You can do it without an animation using transition.

const square = document.getElementById("square");

const leftButton = document.getElementById("left");
leftButton.addEventListener("click", () => {
    square.classList.remove("moveRight");
    square.classList.add("moveLeft");
});

const rightButton = document.getElementById("right")
rightButton.addEventListener("click", () => {
    square.classList.remove("moveLeft");
    square.classList.add("moveRight");
})
#square {
    width: 200px;
    height: 200px;
    background-color: blue;
    margin-top: 20px;
    position: relative;
  transition: transform 1s, opacity 1s;
}
 
 .moveLeft {
   transform: translateX(0);
   opacity: 1;
 }
 
 .moveRight {
  transform: translateX(100px);
   opacity: .5;
 }
<input type="button" id="left" value="MOVE LEFT">
<input type="button" id="right" value="MOVE RIGHT">

<div id="square"></div>
like image 121
Michael Coker Avatar answered Nov 13 '22 15:11

Michael Coker