Transform-Animate CSS Prop with Pure Javascript

Changes the value of a CSS property like the j

by Fernando Testa

HTML

<html>
<body>

<div id="touch-this">
Can touch this!
</div>

</body>
</html>

CSS

body {
  position: relative;
}

#touch-this {
   width: 30px;
   position:fixed;
   padding: 18px 18px 18px 18px;
   background: yellow;
   left: 1000px;
}

JavaScript

function animateCSSProp(el, cssProp, toVal, durationMs) {
      var iId = null;
      var intervMs = 10;

			el = (typeof el === 'string') ? document.querySelector(el) : el;

			var cssPropStr = getComputedStyle(el).getPropertyValue(cssProp);
      var startVal = parseFloat(cssPropStr.split('px')[0]);
      var changeVal = ((toVal - startVal) / durationMs) * intervMs;
      var currentVal = startVal

      function frame() {
          currentVal += changeVal;
          el.style[cssProp] = currentVal + 'px'; // show frame

          if (
              (toVal <= startVal && currentVal <= toVal) ||
              (toVal >= startVal && currentVal >= toVal)
              ) {
            clearInterval(iId);
          }
      }

      iId = setInterval(frame, intervMs); // draw every 10ms
  }
  
  animateCSSProp('#touch-this', 'left', 0, 2000);