jQuery animated number counter from zero to value - javascript

I have created a script to animate a number from zero to it's value.
Working
jQuery
$({ Counter: 0 }).animate({
Counter: $('.Single').text()
}, {
duration: 1000,
easing: 'swing',
step: function() {
$('.Single').text(Math.ceil(this.Counter));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="Single">150</span>
Not Working
I now want to run the script several times on the page for each matching class.
Below is what I am trying but with no success so far:
HTML
<span class="Count">200</span>
<span class="Count">55</span>
JQUERY
$('.Count').each(function () {
jQuery({ Counter: 0 }).animate({ Counter: $(this).text() }, {
duration: 1000,
easing: 'swing',
step: function () {
$(this).text(Math.ceil(this.Counter));
}
});
});

Your thisdoesn'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 $thisin 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

IMPORTANT: It seems like a small difference but you should really use a data attribute to hold the original number to count up to. Altering the original number can have un-intended consequences. For instance, I'm having this animation run everytime an element enters the screen. But if the element enters, exits, and then enters the screen a second time before the first animation finishes, it will count up to the wrong number.
HTML:
<p class="count" data-value="200" >200</p>
<p class="count" data-value="70" >70</p>
<p class="count" data-value="32" >32</p>
JQuery:
$('.count').each(function () {
$(this).prop('Counter', 0).animate({
Counter: $(this).data('value')
}, {
duration: 1000,
easing: 'swing',
step: function (now) {
$(this).text(this.Counter.toFixed(2));
}
});
});

What the code does, is that the number 8000 is counting up from 0 to 8000. The problem is, that it is placed at the middle of quite long page, and once user scroll down and actually see the number, the animation is already dine. I would like to trigger the counter, once it appears in the viewport.
JS:
$('.count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
And HTML:
<span class="count">8000</span>

Here is my solution
and it's also working, when element shows into the viewport
You can see the code in action by clicking jfiddle
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/

If you wanna handle based on if it is int or float
$(".display-counter").each(function () {
$(this)
.prop("Counter", 0)
.animate(
{
Counter: $(this).text()
},
{
duration: 4000,
easing: "swing",
step: function (now, tween) {
// Check added for decimal number
if(parseInt(tween.end) == parseFloat(tween.end)){
$(this).text(Math.ceil(now));
} else{
$(this).text(now.toFixed(2));
}
},
}
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="display-counter">123</p>
<p class="display-counter">125.3</p>

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));
}
});
});

This worked for me
HTML CODE
<span class="number-count">841</span>
jQuery Code
$('.number-count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});

You can do it with animate function in jQuery.
$({ countNum: $('.code').html() }).animate({ countNum: 4000 }, {
duration: 8000,
easing: 'linear',
step: function () {
$('.yourelement').html(Math.floor(this.countNum));
},
complete: function () {
$('.code').html(this.countNum);
//alert('finished');
}
});
Demo

This is working for me
$('.Count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});

This is work for me !
<script type="text/javascript">
$(document).ready(function(){
countnumber(0,40,"stat1",50);
function countnumber(start,end,idtarget,duration){
cc=setInterval(function(){
if(start==end)
{
$("#"+idtarget).html(start);
clearInterval(cc);
}
else
{
$("#"+idtarget).html(start);
start++;
}
},duration);
}
});
</script>
<span id="span1"></span>

$({ Counter: 0 }).animate({
Counter: $('.Single').text()
}, {
duration: 1000,
easing: 'swing',
step: function() {
$('.Single').text(Math.ceil(this.Counter));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="Single">150</span>

Related

How can I change number format to decimals in JS

I have this counter and I need it to be in decimals (instead of having 150000000 I'd like to have 150.000.000,00 or at least 150.000.000).
I tried replace this:
step: function() {
$this.text(Math.floor(this.countNum));
}
with this:
formatter: function (value, options) {
return value.toFixed(options.decimals);
}
but it didn't work. What can I do?
These are parts of my js and html interested by this:
var a = 0;
$(window).scroll(function() {
var oTop = $('#counter').offset().top - window.outerHeight/2;
if (a == 0 && $(window).scrollTop() > oTop) {
euro.className = "testo one column hide"
$('.counter-value').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
},
{
duration: 2000,
easing: 'swing',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
//alert('finished');
}
});
});
a = 1;
} else {
euro.className = "testo one column show"
}
});
<div id="counter" class="two columns counter-value" data-count="150000000">
</div>
toFixed is a good method, but it will only take care of the decimals at the end. To accomplish what you are describing you may want to use number.toLocaleString(). So your formatter would look like:
formatter: function(value, options) {
return value.toLocaleString(options);
}
You can check out the toLocaleString options in the MDN docs below:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
Hope that helps!

Jquery Flexslider with Sliding effect

jQuery(document).ready(function ($) {
$('.flexslider.wsc_banner4519').each(function () {
var _this = this;
$('.slides > li', this).hide();
$(this).flexslider($.extend({}, {
animation: 'fade',
slideshow: false,
slideshowSpeed: 7000,
pagination: true,
directionNav: false,
animationDuration: 600
}, {
before: function (slider) {
var descs = $(_this).next('.descriptions').find('article');
if (slider.animatingTo != slider.currentSlide && descs.length >= slider.slides.length) {
descs.filter(':visible').fadeOut(slider.vars.animationDuration / 2, function () {
descs.eq(slider.animatingTo).fadeIn(slider.vars.animationDuration / 2);
});
}
}
})).hover(function () {
$('.flex-direction-nav', this).stop(true).fadeTo(100, 1);
}, function () {
$('.flex-direction-nav', this).stop(true).fadeTo(100, 0);
});
});
});
I am using flexslider(converted to double slider).Here both have fade-out effect.
I want image to be fade out and text to be sliding.
http://demo2.websitescreative.com/responsive/Features/sliderwithtext.aspx
Like this demo I have done. I want to change this into the effect I described above.
PLEASE Help.

Why is this counting down after reaching the target?

I wanted to have a counter that only activates when actually on the screen. I've managed to mangle this together from other examples I've found.
HTML:
<div>Scroll Down</div>
<span class="count">200</span>
CSS:
div {
height:800px;
background:red;
}
h1 {
display:none;
}
Javascript:
$(window).scroll(function() {
var hT = $('#scroll-to').offset().top,
hH = $('#scroll-to').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
console.log((hT - wH), wS);
if (wS > (hT + hH - wH)) {
$('.count').each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function(now) {
$(this).text(Math.ceil(now));
}
});
});
}
});
DEMO:
https://jsfiddle.net/76d57vjL/
The problem is, it reaches 200 and then counts back down to 0 but I want it to just stay at 200. I can't seem to figure out whats actually causing it though.
The problem was that you were creating more than 1 animation, so going back to 1 after starting the count, i fixed it with a flag, but probably you could make something with the heights to check that out.
Here's the fix with the flag: https://jsfiddle.net/uc0av8fh/
var flag = true;
$(window).scroll(function() {
$('#scroll-to');
var hT = $('#scroll-to').offset().top,
hH = $('#scroll-to').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
console.log((hT-wH) , wS);
if (wS > (hT+hH-wH)){
$('.count').each(function () {
if(!flag) return;
//console.log();
flag = false;
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
return 1;
}
});
});
}
});

Jquery Number counting slowdown animation when target reach

$(this).prop('Counter', 0).animate({
Counter: 123456789
}, {
duration: 2000,
easing: 'easeOutBack',
step: function (now) {
$(this).html(parseFloat(now).toFixed(2));
},
complete: function () {
}
});
In this code number running same speed till ends. I need the number running speed will slow down when reached the target.
You can make a variable for speed and incrase this with step. In your exemple is:
var speed = 2000;
$(this).prop('Counter', 0).animate({
Counter: 123456789
}, {
duration: speed,
easing: 'easeOutBack',
step: function (now) {
$(this).html(parseFloat(now).toFixed(2));
if(counter < 1000){
speed += 100;
}
},
complete: function () {
}
});

jQuery number counter

I'm using this jQuery snippet to animate a number counter from 0 to to the number provided in the span. Could someone show me how to modify it to get numbers to count DOWN to 0 when starting at a given value?
<span class="count">200</span>
$('.count').each(function () {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
Something like this? I'm assuming that 'now' in the step function is just counting steps.
$('.count').each(function () {
$(this).data('start', parseInt($(this).text())).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text($(this).data(start) - now);
}
});
});
I verified this works in jsFiddle (https://jsfiddle.net/0mtht3xm/):
$('.count').each(function () {
$(this).data('start', parseInt($(this).text())).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text($(this).data('start') - Math.ceil(now));
}
});
});
There are countless different ways to create a counter that counts down to 0. This is just how I would do it:
HTML:
<span class="count">200</span>
JS:
var $count = $('.count');
var num = parseInt($count.text());
var interval = window.setInterval(updateTime, 1000);
function updateTime() {
num--;
$count.text(num.toString());
if (num <= 0) {
window.clearInterval(interval);
}
}

Categories

Resources