Number Countup Animation With Vanilla JavaScript – Animated Counter

Category: Animation , Javascript | May 6, 2021
Author:lukaofirst
Views Total:15,597 views
Official Page:Go to website
Last Update:May 6, 2021
License:MIT

Preview:

Number Countup Animation With Vanilla JavaScript – Animated Counter

Description:

Just another animated counter JavaScript library for animating counting up to a given number.

How to use it:

1. Add the CSS class counter to the container which holds the initial value, and then specify the number to which the counter counts up in the data-target attribute:

<div class="counter" data-target="300000">1000</div>
<div class="counter" data-target="200000">0</div>

2. Apply the countup animation to the element and done.

// Selector
const counters = document.querySelectorAll('.counter');
// Main function
for(let n of counters) {
  const updateCount = () => {
    const target = + n.getAttribute('data-target');
    const count = + n.innerText;
    const speed = 5000; // change animation speed here
    const inc = target / speed; 
    if(count < target) {
      n.innerText = Math.ceil(count + inc);
      setTimeout(updateCount, 1);
    } else {
      n.innerText = target;
    }
  }
  updateCount();
}

You Might Be Interested In:


One thought on “Number Countup Animation With Vanilla JavaScript – Animated Counter

  1. Isa Sayed

    Excellent example on the internet to show countdown for big number.
    but how to start the counter on focus.

    Reply

Leave a Reply