I want to create an animation circle that play always and allow click even

  css, html, javascript

Hello guys I want my animation be infinite and when it finish – he restart without any jump space.
and moreover allow to click event to go next position on my animation circle
How can I apply it?

let jump = 0;
let index = 0;

const boxContainer = document.querySelector(".boxContainer");

const animate = () => {
  boxContainer.style.transform = `translate(${jump}px)`;
  boxContainer.appendChild(boxContainer.children[index].cloneNode(true));
  index++;
};

const nextBox = () => {
  jump -= 100;
  requestAnimationFrame(animate);
};
body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.container {
  background-color: aqua;
  height: fit-content;
  width: 500px;
  overflow-x: hidden;
  position: relative;
}

.anim {
  animation: anim 10s infinite linear;
}

.boxContainer {
  display: flex;
  transition: transform 0.2s;
}

.boxContainer > .box {
  width: 90px;
  height: 90px;
  margin: 5px;
  background-color: blue;
  flex-shrink: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
}

.container > button {
  position: absolute;
  left: 0px;
  top: 32px;
  width: 50px;
}

@keyframes anim {
  to {
    transform: translateX(-1000px);
  }
}
<div class="container">
  <div class="anim">

    <div class="boxContainer">
      <div class="box">1</div>
      <div class="box">2</div>
      <div class="box">3</div>
      <div class="box">4</div>
      <div class="box">5</div>
      <div class="box">6</div>
      <div class="box">7</div>
      <div class="box">8</div>
      <div class="box">9</div>
      <div class="box">10</div>
      <div class="box">11</div>
      <div class="box">12</div>
      <div class="box">13</div>
      <div class="box">14</div>
      <div class="box">15</div>
      <div class="box">16</div>
    </div>
  </div>
  <button onclick="nextBox()">next box</button>
</div>

As you can see I create at animation that allow that click event nad he jump to next position but in some place animation restart in wrong place.

How to fix that issue in right and performance way ?

Source: Ask Javascript Questions

LEAVE A COMMENT