I have created a script to animate a number from zero to it\'s value.
jQuery
Here is my solution and it's also working, when element shows into the viewport
var counterTeaserL = $('.go-counterTeaser');
var winHeight = $(window).height();
if (counterTeaserL.length) {
var firEvent = false,
objectPosTop = $('.go-counterTeaser').offset().top;
//when element shows at bottom
var elementViewInBottom = objectPosTop - winHeight;
$(window).on('scroll', function() {
var currentPosition = $(document).scrollTop();
//when element position starting in viewport
if (currentPosition > elementViewInBottom && firEvent === false) {
firEvent = true;
animationCounter();
}
});
}
//counter function will animate by using external js also add seprator "."
function animationCounter(){
$('.numberBlock h2').each(function () {
var comma_separator_number_step = $.animateNumber.numberStepFactories.separator('.');
var counterValv = $(this).text();
$(this).animateNumber(
{
number: counterValv,
numberStep: comma_separator_number_step
}
);
});
}
https://jsfiddle.net/uosahmed/frLoxm34/9/
You can get the element itself in .each()
, try this instead of using this
$('.Count').each(function (index, value) {
jQuery({ Counter: 0 }).animate({ Counter: value.text() }, {
duration: 1000,
easing: 'swing',
step: function () {
value.text(Math.ceil(this.Counter));
}
});
});
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));
}
this
inside the step callback isn't the element but the object passed to animate()
$('.Count').each(function (_, self) {
jQuery({
Counter: 0
}).animate({
Counter: $(self).text()
}, {
duration: 1000,
easing: 'swing',
step: function () {
$(self).text(Math.ceil(this.Counter));
}
});
});
Another way to do this and keep the references to this
would be
$('.Count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 1000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
FIDDLE