Search code examples
javascriptcsscss-animationscss-transformskeyframe

How to control the transform distance with pure JavaScript


I made this http://codepen.io/adamchenwei/pen/dOvJNX

and I try to apply a certain way of moving for a dom so it move for a fixed distance and stop, instead of animate and move through the whole width of the dom. However, I don't really want to fix the distance inside the css keyframe because I need to detect that distance dynamically, since my div that got animated ideally will change the width dynamically as well since that is not going always be 100% or any specific px fixed.

Is there way I can do that in JavaScript instead and not let css to take charge in this transform distance part? Cross browser capacity will be great.

SCSS

.myItem {
  height: 100px;
  width: 501px;
  background-color: beige;
  animation: to-left-transition 300ms;
  animation-iteration-count: 1;
  animation-fill-mode: forwards;
  animation-timing-function: ease-in-out;
}


@keyframes to-left-transition {
  0% {
    transform: translate(0);
  }
  100% {
    transform: translate(100%);
  }
}

HTML

<div class="myItem">
  stuff here

</div>

Solution

  • Found out a better way. Soooooo much easier! I should have been using transition instead of animation. As that give me the flexibility to adjust the animation accordingly.

    Hope it helps someone else to save couple hours!

    http://codepen.io/adamchenwei/pen/xRqYNj

    HTML

    <div class="myItem">
      stuff here
    
    </div>
    

    CSS

    .myItem {
      position: absolute;
      height: 100px;
      width: 501px;
      background-color: beige;
      transition: transform 1s;  
    }
    

    JS

    setTimeout(function() {
      document.getElementsByClassName('myItem')[0].style.transform="translateX(400px)";
      console.log('ran');
    }, 3000);