JSFiddle - React, Tailwind, and code Playground
by Travis Almand
HTML
<div id="num">1234</div>
JavaScript
(function($) {
$.fn.animateNumbers = function(stop, commas, duration, ease, append) {
return this.each(function() {
var $this = $(this);
var isInput = $this.is('input');
var start = parseInt(isInput ? $this.val().replace(/,/g, "") : $this.text().replace(/,/g, ""));
var regex = /(\d)(?=(\d\d\d)+(?!\d))/g;
commas = commas === undefined ? true : commas;
// number inputs can't have commas or it blanks out
if (isInput && $this[0].type === 'number') {
commas = false;
}
$({value: start}).animate({value: stop}, {
duration: duration === undefined ? 1000 : duration,
easing: ease === undefined ? 'swing' : ease,
step: function() {
isInput ? $this.val(Math.floor(this.value)) : $this.text(Math.floor(this.value));
if (commas) {
isInput ? $this.val($this.val().replace(regex, '$1,')) : $this.text($this.text().replace(regex, "$1,"));
}
if (append) {
$this.text($this.text() + append);
}
},
complete: function() {
if (parseInt($this.text()) !== stop || parseInt($this.val()) !== stop) {
isInput ? $this.val(stop) : $this.text(stop);
if (commas) {
isInput ? $this.val($this.val().replace(regex, '$1,')) : $this.text($this.text().replace(regex, "$1,"));
}
}
if (append) {
$this.text($this.text() + append);
}
}
});
});
};
})(jQuery);
$("#num").animateNumbers(4321, false, 1500, null, '+');