skip to Main Content

On a site I have a number counter that always increases, without any fancy animation. Now I need to animate it every time the number updates, like this:

enter image description here

Which HTML (+CSS +JS if needed) code can I use for this? Thanks!

P.S.: The number has 2 decimals and uses "," as a decimal separator.

2

Answers


  1. You can achieve this effect using HTML, CSS, and JavaScript. Here’s a simple example:

    HTML:

    <div class="counter">
      <span id="number">0.00</span>
    </div>
    

    CSS:

    .counter {
      font-family: Arial, sans-serif;
      font-size: 36px;
      font-weight: bold;
    }
    
    .counter #number {
      display: inline-block;
      overflow: hidden;
    }
    

    JavaScript:

    function animateNumber(from, to, duration) {
      let start = new Date().getTime();
      let timer = setInterval(function() {
        let now = new Date().getTime();
        let timePassed = now - start;
        if (timePassed >= duration) {
          clearInterval(timer);
          timePassed = duration;
        }
        let progress = timePassed / duration;
        let result = Math.floor((to - from) * progress + from * 100) / 100;
        document.getElementById('number').textContent = result.toFixed(2).replace('.', ',');
        if (progress === 1) clearInterval(timer);
      }, 10);
    }
    
    // Example usage:
    animateNumber(0, 1234.56, 2000); // Change 1234.56 to your desired number and 2000 to the duration in milliseconds
    

    This code will create a counter with a specified starting number (0 in this case) and animate it to a specified ending number (1234.56 in this case) over a specified duration (2000 milliseconds in this case).

    You can adjust the HTML, CSS, and JavaScript code as needed to fit your specific requirements and styling preferences.

    You can have basic concept from this : https://www.geeksforgeeks.org/how-to-make-animated-counter-using-javascript/

    Login or Signup to reply.
  2. According to the illustration, this already unmaintained library came to mind:

    Example

    const el = document.querySelector('.odometer')
     
    const od = new Odometer({
      el: el,
      value: 1234, // default value
     
      // Any option (other than auto and selector) can be passed in here
      format: '( ddd),dd',
      theme: 'default',
      duration: 3000,
    })
     
    // change to new value
    od.update(9876)
    // or
    el.innerHTML = 9876
    <link rel="stylesheet" href="http://github.hubspot.com/odometer/themes/odometer-theme-default.css" />
    <script src="http://github.hubspot.com/odometer/odometer.js"></script>
    
    <div class="odometer"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search