shako
shako

Reputation: 31

How can I make number counter to count multiple elements in Wix Velo

I'm making a website on Wix and it has Velo which works like javascript (I don't understand much in coding)

I was trying to do a number counter which counts from 0 to a given number and I did it, but I need 4 different counters not sure how to do it maybe someone can help, please.

so my code looks like this

$w.onReady(function() {});

let startNum = 0;
let endNum = 145;
const duration = 20;

$w.onReady(function() {
  setInterval(() => {
    countUp();
  }, duration);
});


function countUp() {
  if (startNum <= endNum) {
    $w('#StartNumber').text = startNum.toString();
    startNum++;
  }
}

#startnumber is a text element that goes from 0 to 145 I want to do the same with 3 more elements #startnumber2, 3, and 4.

this is what I'm trying to do

Upvotes: 3

Views: 893

Answers (1)

Mosh Feu
Mosh Feu

Reputation: 29287

The counting logic can be extracted to a function so you could call it for all the text components.

$w.onReady(function () {
  count($w('#text1'), 0, 150, 1000);
  count($w('#text2'), 0, 250, 1000);
  count($w('#text3'), 0, 500, 1000);
  count($w('#text4'), 0, 1000, 1000);
});

function count(obj, start, end, duration) {
  let startTimestamp = null;
  const step = (timestamp) => {
    if (!startTimestamp) startTimestamp = timestamp;
    const progress = Math.min((timestamp - startTimestamp) / duration, 1);
    obj.text = `${Math.floor(progress * (end - start) + start)}`;
    if (progress < 1) {
      requestAnimationFrame(step);
    }
  };
  requestAnimationFrame(step);
}

Demo: https://moshef9.wixsite.com/count-numbers

The counter function is taken from: https://stackoverflow.com/a/60291224/863110

Upvotes: 1

Related Questions