jQuery animated number counter from zero to value
Your this
doesn't refer to the element in the step callback, instead you want to keep a reference to it at the beginning of your function (wrapped in $this
in my example):
$('.Count').each(function () {
var $this = $(this);
jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
duration: 1000,
easing: 'swing',
step: function () {
$this.text(Math.ceil(this.Counter));
}
});
});
Update: If you want to display decimal numbers, then instead of rounding the value with Math.ceil
you can round up to 2 decimals for instance with value.toFixed(2)
:
step: function () {
$this.text(this.Counter.toFixed(2));
}
jQuery/JS number counting animation from zero to value
Reviewing your code:
Since the there is no logic to dictate how the counter should change, i've added a countTo
variable before the animation.
Since you reference { Counter: $(this).text() }
as the properties object within the animate function, the $(this).text()
begins as {{ confirmed }}
which is not a parsable number, hence NaN
.
The solution below should resolve this.
$('.count').each(function () { let el = $(this); let countTo = 1000; el.prop('counter',0).animate({ counter: `+=${countTo}` }, { step: function (now) { $(this).text(Math.ceil(now)) },
}); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><h4 class="font-weight-bold" style="color:#f92424"><span class="count">{{ confirmedIn }}</span></h4>
jQuery animated number counter from zero to a certain number returned in a PHP function
EDIT
I changed a coupled things from my first answer...
The trick, to show an "achievement counter" will be to count from zero to the number obtained via ajax on page load.
Then the interval to constantly check for an updated achievement has to check if the quite long onload animation had finished.
If not finished the initial counting... Just let it finish! And wait for the next inteval iteration.
Then... If the obtained number is different from the number "before ajax", count!
The speed now depends on the number form the ressource speed to increase.
I think that is closer to what you wish...
;)
(function($){ console.clear(); var number_beforeAjax; var number_afterAjax;
var auto_refresh = setInterval( function (){ number_beforeAjax = parseInt( $("#tasksCompleted").text().replace(",","") ); console.log("number_beforeAjax: "+number_beforeAjax); $.ajax({ dataType: "jsonp", url: "https://www.bessetteweb.com/SO/45614889/ressource.php", success: function(data){ $("#numberFromAjax").html(data); counter(); } }); //$("#numberFromAjax").getJSON("https://www.bessetteweb.com/SO/45614889/ressource.php",counter()); }, 3000); // refresh every 3000 milliseconds
// A separate function to call as a load callback function counter(){
// Just to see what was loaded via ajax. var loaded = $("#numberFromAjax").text(); console.log("loaded: "+loaded);
// Number loaded via ajax parsed as integer. number_afterAjax = parseInt( $("#numberFromAjax").text().replace(",","") ); console.log("number_afterAjax: "+number_afterAjax);
// If the numbers before and after ajax are different if(number_beforeAjax != number_afterAjax && !isNaN(number_afterAjax) ) { counterSpeed = 5000; // Faster if the difference isn't much if(number_afterAjax-number_beforeAjax<20){ counterSpeed = 2900; } // Set the start number to zero on 1st iteration var startNumber; if(isNaN(number_beforeAjax)){ startNumber = 0; }else{ startNumber = number_beforeAjax; }
// Counter! jQuery({ Counter: startNumber }).animate({ Counter: number_afterAjax }, { duration: counterSpeed, easing: "swing", step: function () { $("#tasksCompleted").text(Math.ceil(this.Counter).toLocaleString()); } }); }
// Just a console.log if(number_beforeAjax == number_afterAjax && !isNaN(number_afterAjax)){ console.log("Request revealed no change.") } }})(jQuery);
#numberFromAjax{ display:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="tasksCompleted"></span><br><span id="numberFromAjax"></span>
Animated counter when scrolling into viewport - with thousands separator
To get your thousands - comma separated string use Number.prototype.toLocaleString()
console.log( (12345678).toLocaleString('en-US') );
Animating counter from zero with commas
You can add
.toLocaleString('en')
To the step property:
step: function(now) {
$(this).text(Math.ceil(now).toLocaleString('en'));
}
You can also pass in navigator.language rather than 'en' and the decimals will be displayed according to the users browser language setting.
Start animated number counter with JQuery when someone scrolls to ID
To determine if scrolling has gone past a certain element you can compare the window scroll position + height, to the vertical offset of the target element. Try this:
$(window).scroll(startCounter);
function startCounter() {
let scrollY = (window.pageYOffset || document.documentElement.scrollTop) + window.innerHeight;
let divPos = document.querySelector('#counter-container').offsetTop;
if (scrollY > divPos) {
$(window).off("scroll", startCounter);
$('.count').each(function() {
var $this = $(this);
jQuery({
Counter: 0
}).animate({
Counter: $this.text().replace(/,/g, '')
}, {
duration: 1000,
easing: 'swing',
step: function() {
$this.text(commaSeparateNumber(Math.floor(this.Counter)));
},
complete: function() {
$this.text(commaSeparateNumber(this.Counter));
//alert('finished');
}
});
});
function commaSeparateNumber(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
}
}
#spacer {
height: 1000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Scroll down...
<div id="spacer"></div>
<div id="counter-container">
<span class="count">6,000</span>
<span class="count">600</span>
<span class="count">60</span>
</div>
Related Topics
Angular 2: How to Detect Changes in an Array? (@Input Property)
Chrome Extension - How to Get Http Response Body
How to Force Angular2 to Post Using X-Www-Form-Urlencoded
Javascript: How to Validate Dates in Format Mm-Dd-Yyyy
Keyword 'Const' Does Not Make the Value Immutable. What Does It Mean
How to Create Every Combination Possible for the Contents of Two Arrays
How to Convert Raw JavaScript Object to a Dictionary
Http Status Code 401 Even Though I'm Sending Credentials in the Request
How to Sequentially Run Promises with Q in JavaScript
Access JavaScript Nested Objects Safely
How to Implement a Stack and a Queue in JavaScript
Syntax for an Async Arrow Function
Obtain Form Input Fields Using Jquery
Screen Scraping from a Web Page with a Lot of JavaScript
Why Does a Form with One Text Input Submit on Enter While One with Two Text Inputs Does Not