How to convert jQuery animate function to pure JS

Viewed 802

I have this simple jquery logic, How would I convert that into pure javascript?

Besides I have to use this code in React with Typescript.

I have no clue where to start unfortunately. Any help would be extremely appreciated.


$('.counting').each(function() {
  var $this = $(this),
      countTo = $this.attr('data-count');
  
  $({ countNum: $this.text()}).animate({
    countNum: countTo
  },

  {
    duration: 3000,
    easing:'linear',
    step: function() {
      $this.text(Math.floor(this.countNum));
    },
    complete: function() {
      $this.text(this.countNum);
      //alert('finished');
    }
  });  
});

I've converted that until start animate function..

let counting = document.querySelectorAll(".counting");
let countingArray = Array.prototype.slice.call(counting);

countingArray.forEach((el) => {
  let   countTo = el.getAttribute("data-count");

//start animate...

I referred this code in https://codepen.io/shvvffle/pen/JRALqG

1 Answers

An animation function for you:

function animate(render, from, to, duration, timeFx) {
  let startTime = performance.now();
  requestAnimationFrame(function step(time) {
    let pTime = (time - startTime) / duration;
    if (pTime > 1) pTime = 1;
    render(from + (to - from) * timeFx(pTime));
    if (pTime < 1) {
      requestAnimationFrame(step);
    }
  });
}
  • render is the callback function with which you expect to update new values;
  • from and to are the initial values and the target values of your animation;
  • duration is the continuance of the animation in time in miliseconds;
  • timeFx is the timing function from [0, 1] to [0, 1].

You may use it as:

countingArray.forEach((el) => {
  let countTo = el.getAttribute("data-count");
    animate(function(newValue) {
        el.innerText = Math.floor(newValue);
    }, 0, countTo, 3000, x => x);
});
Related