Comma placement in animated number counter
P粉277824378
P粉277824378 2024-01-16 14:43:34
0
1
570

I've been trying different combinations of HTML, CSS, and JavaScript that would give me a scrolling animated number counter with a symbol next to each number ( , %, etc.). I finally found the right combination; however, it's not perfect yet. I want to add commas to numbers 1,000 and above, but when I add commas in HTML, it generates NaN output. I'm very new to JavaScript and I don't know what to add or fix in my current code to display commas.

Can anyone rewrite my current code to display commas or guide me on how to do this? I would be very grateful for any help!

<script>
function inVisible(element) {
  //Checking if the element is
  //visible in the viewport
  var WindowTop = $(window).scrollTop();
  var WindowBottom = WindowTop + $(window).height();
  var ElementTop = element.offset().top;
  var ElementBottom = ElementTop + element.height();
  //animating the element if it is
  //visible in the viewport
  if ((ElementBottom <= WindowBottom) && ElementTop >= WindowTop)
    animate(element);
}

function animate(element) {
  //Animating the element if not animated before
  if (!element.hasClass('ms-animated')) {
    var maxval = element.data('max');
    var html = element.html();
    element.addClass("ms-animated");
    $({
      countNum: element.html()
    }).animate({
      countNum: maxval
    }, {
      //duration 2 seconds
      duration: 2000,
      easing: 'linear',
      step: function() {
        element.html(Math.floor(this.countNum) + html);
      },
      complete: function() {
        element.html(this.countNum + html);
      }
    });
  }
}
//When the document is ready
$(function() {
  //This is triggered when the
  //user scrolls the page
  $(window).scroll(function() {
    //Checking if each items to animate are
    //visible in the viewport
    $("h2[data-max]").each(function() {
      inVisible($(this));
    });
  })
});
</script>

P粉277824378
P粉277824378

reply all(1)
P粉211273535

Remove commas when reading HTML and add them back when displaying.

function animate(element) {
  //Animating the element if not animated before
  if (!element.hasClass('ms-animated')) {
    var maxval = element.data('max');
    var html = element.html();
    element.addClass("ms-animated");
    $({
      countNum: parseInt(element.html().replace(/,/g, '')) // remove commas
    }).animate({
      countNum: maxval
    }, {
      //duration 2 seconds
      duration: 2000,
      easing: 'linear',
      step: function() {
        element.html((Math.floor(this.countNum) + html).toLocaleString());
      },
      complete: function() {
        element.html((Math.floor(this.countNum) + html).toLocaleString());
      }
    });
  }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template