Search code examples
htmlcsskeyframejss

How to change speed of a keyframe without it jumping


I am trying to change the speed of the keyframe by changing animationDuration. but everytime i change the animationDuration, the box that is animated changes positions(jumps). Is there any way to change the speed without of it jumping? Thank you in advance. The code is here, im sry for not seperating them to js/css/html files.

var styles;

function togglePlayState(newState) {
  document.getElementById("boxx").style.animationPlayState = newState;
}

var sliderSpeed = document.getElementById("MoveSpeed");
sliderSpeed.oninput = function() {
  styles = window.getComputedStyle(boxx);
  document.getElementById('boxx').style.animationDuration = +sliderSpeed.value.toString() + "s";
  console.log(sliderSpeed.value + "s");
  console.log(styles);
}
body {
  height: 100%;
  top: 0px;
  left: 0px;
  margin-top: 0%;
  margin-left: 0%;
}

.parent {
  background-color: rgb(0, 0, 0);
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  margin: 0%;
}

.boxx {
  background-color: red;
  position: relative;
  height: 50px;
  width: 50px;
  animation: left-to-right 3s forwards infinite alternate linear;
}

.start-animation {
  animation: left-to-right 3s forwards infinite alternate linear;
}

.paused {
  animation-play-state: paused;
}

@keyframes botleft-to-topright {
  /*Koumpi katw aristera Panw deksia*/
  0% {
    left: 0;
    top: calc(100% - 50px);
  }
  100% {
    left: calc(100% - 50px);
    top: 0;
  }
}

@keyframes left-to-right {
  0% {
    left: 0;
    top: 0;
  }
  100% {
    left: calc(100% - 50px)
  }
}
<div class="parent">

  <div class="boxx" id="boxx"></div>
  <button onclick="togglePlayState('Paused');">Pause Animation</button>
  <!-- Play Pause Buttons  -->
  <button onclick="togglePlayState('Running');">Continue Animation</button>
  <!-- Play Pause Buttons  -->
  <div class="slidecontainer">
    <input type="range" min="1" max="15" value="1" class="slider" id="MoveSpeed">
  </div>
</div>


Solution

  • It is not possible to do that mid animation with pure css animations. In order to do that you would need to use a js animation library like GSAP. See this answer for an example.