I have these below counter js function. It's working OK.
But now when I try to add the new value to $(".set")
to 30, the counter is reset from 0 until 30.
What I need is just continue the counter from the last state (25) to 30 (with animate) without reset the counter.
How to do the best way for this?
$.fn.counter = function(){
var $el = this;
$el.prop('Counter',0).animate({
Counter: $el.text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$el.text(Math.ceil(now));
}
});
};
$(".set").counter();
$('#add').on('click', function(e) {
$(".set").text(30);
$(".set").counter();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >25</div>
<button id="add">Add to 30</div>
CodePudding user response:
If you want to continue the animation adding another delay of custom duration, one option is to add a parameter start
to the counter
function to define the number it should begin counting.
$.fn.counter = function(start){
var $el = this;
$el.prop('Counter',start).animate({
Counter: $el.text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$el.text(Math.ceil(now));
}
});
};
$(".set").counter(0);
$('#add').on('click', function(e) {
$(".set").text(30);
$(".set").counter(25);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >25</div>
<button id="add">Add to 30</div>
Now at any time you click the button, it will start counting from 0
to 25
within 4000
ms and it will continue from the last value up to 30
with another animation of the same duration.