Home > Enterprise >  Loop a sequence of css animation
Loop a sequence of css animation

Time:01-03

I have the following code:

@keyframes ball1 {
  0% {
    transform: translateX(0px);
    opacity: 0%;
  }
  50% {
    opacity: 100%;
  }
  100% {
    transform: translateX(120px);
    opacity: 0%;
  }
}

@keyframes ball2 {
  0% {
    transform: translateX(0px);
    opacity: 0%;
  }
  50% {
    opacity: 100%;
  }
  100% {
    transform: translateX(160px);
    opacity: 0%;
  }
}

@keyframes ball3 {
  0% {
    transform: translateX(0px);
    opacity: 0%;
  }
  50% {
    opacity: 100%;
  }
  100% {
    transform: translateX(200px);
    opacity: 0%;
  }
}

@keyframes ball4 {
  0% {
    transform: translateX(0px);
    opacity: 0%;
  }
  50% {
    opacity: 100%;
  }
  100% {
    transform: translateX(240px);
    opacity: 0%;
  }
}

.ball {
  background: black;
  width: 20px;
  height: 20px;
  border-radius: 20px;
  margin: 10px;
  animation-duration: 1s;
  animation-iteration-count: 1;
}

#ball-1 {
  animation-name: ball1;
}

#ball-2 {
  animation-name: ball2;
  animation-delay: 1s;
}

#ball-3 {
  animation-name: ball3;
  animation-delay: 2s;
}

#ball-4 {
  animation-name: ball4;
  animation-delay: 3s;
}
<div  id="ball-1"></div>

<div  id="ball-2"></div>

<div  id="ball-3"></div>

<div  id="ball-4"></div>

I want to achieve to follow:

  1. Sequence starts
  2. Ball 1 animates once.
  3. There is a delay of 1 second.
  4. Ball 2 animates once.
  5. There is a delay of 1 second.
  6. Ball 3 animates once.
  7. There is a delay of 1 second.
  8. Ball 4 animates once.
  9. There is a delay of 1 second.
  10. The sequence restarts from step 1.

This is what I currently have, but I don't know how to loop this sequence, it only plays ones. Not sure if it's possible with only css. If not I'm fine with JS as well.

Example: https://jsfiddle.net/patxh1gn/

CodePudding user response:

do you mean something like this?

@keyframes ball1 {
  0%,
  12.501% {
    transform: translateX(0px);
    opacity: 0%;
  }
  6.25%,
  12.502%,
  100% {
    opacity: 100%;
  }
  12.5% {
    transform: translateX(var(--right));
    opacity: 0%;
  }
}

.ball {
  background: black;
  width: 20px;
  height: 20px;
  border-radius: 20px;
  margin: 10px;
  animation: ball1 8s infinite;
}

#ball-1 {
  --right: 120px;
}

#ball-2 {
  --right: 160px;
  animation-delay: 2s;
}

#ball-3 {
  --right: 200px;
  animation-delay: 4s;
}

#ball-4 {
  --right: 240px;
  animation-delay: 6s;
}
<div  id="ball-1"></div>

<div  id="ball-2"></div>

<div  id="ball-3"></div>

<div  id="ball-4"></div>

CodePudding user response:

You can loop the animation by setting the animation-iteration-count property to infinite. You can do this by adding the following line to the .ball class:

animation-iteration-count: infinite;

Alternatively, you can also set it for each individual ball, for example:

 #ball-1 {
  animation-name: ball1;
  animation-iteration-count: infinite;
}
  • Related