Count Up To Any Number With Smooth Animation In JavaScript – Number-CounteUp

Category: Animation , Javascript | March 26, 2024
Author:debu100
Views Total:163 views
Official Page:Go to website
Last Update:March 26, 2024
License:MIT

Preview:

Count Up To Any Number With Smooth Animation In JavaScript – Number-CounteUp

Description:

This is a neat little JavaScript function that allows you to create an animated number counter with just a touch over ten lines of JavaScript.

You specify a target number, and the script incrementally counts up from zero (or whatever starting point you set) until it reaches that target value. Ideal for vividly displaying statistics like total users, financial goals, completed tasks, and more.

How to use it:

1. Add a data-target attribute to an HTML element containing the number you want to count up to.

<h2 class="count" data-target="12345">0</h2>

2. The JavaScript grabs all elements with a .count class, and runs an update() function on each one. This update() function gets the target number from the data-target, calculates the increment amount based on a speed value you set, and uses setTimeout() to update the text content on each animation frame until hitting the target.

const counts = document.querySelectorAll(".count");
const speed = 397;
counts.forEach((count) => {
  function upDate() {
    const target = Number(count.getAttribute("data-target"));
    const counter = Number(count.innerText);
    const inc = target / speed;
    if (counter < target) {
      count.innerText = Math.floor(inc + counter);
      setTimeout(upDate, 15);
    } else {
      count.innerText = target;
    }
  }
  upDate();
});

You Might Be Interested In:


Leave a Reply