Search code examples
javascriptjqueryfor-loopcountersetinterval

jquery Counter is not starting from 0 to the target number


Trying to create counter which starts from 0 and go up to target value. I tried to Use setInterval but it didn't work, As I do not have much clear idea of it I have referred certain tutorial also still not able to work my code. If someone can help me by correcting my code would be great for me. Thank You In Advance.

$(document).ready(function() {
    $('.tts-counter .tts-counter-item .tts-number').each(function() {
        var counterValue = $(this).data('counter');
        var finalValue = 0;
        for (var i = 0; i <= counterValue; i++) {
            $(this).text(finalValue);
            finalValue++;
        }
    });
});

Solution

  • After checking and referring to many articles related to counters I found this solution.

    $('.tts-number').each(function() {
                    $(this).prop('Counter', 0).animate({
                        Counter: $(this).text()
                    }, {
                        duration: 4000,
                        easing: 'swing',
                        step: function(now) {
                            $(this).text(Math.ceil(now));
                        }
                    });
                });