I want to animate a counter from 0 to a given value automatically on page load. Recently I found one but it works with button click.
var amount=parseInt($('#amount').val());
var i = parseInt($('#count').val());
var tim;
function run(){
tim = setInterval(function(){
if(i>=amount){clearInterval(tim); return;}
$('#count').val(++i);
},100);
}
$('#runner').click(function(){
run();
});
SEE >> JS fiddle DEMO
Also I want to add a reset button in it which will run it again from 0 on every click.
I want to animate a counter from 0 to a given value automatically on page load. Recently I found one but it works with button click.
var amount=parseInt($('#amount').val());
var i = parseInt($('#count').val());
var tim;
function run(){
tim = setInterval(function(){
if(i>=amount){clearInterval(tim); return;}
$('#count').val(++i);
},100);
}
$('#runner').click(function(){
run();
});
SEE >> JS fiddle DEMO
Also I want to add a reset button in it which will run it again from 0 on every click.
Share Improve this question edited Jul 25, 2016 at 5:03 Darren 70.8k24 gold badges140 silver badges145 bronze badges asked Mar 15, 2013 at 12:38 Satinder SinghSatinder Singh 291 gold badge1 silver badge10 bronze badges 1- The answer is in your title. Call it on page load. lol – epascarello Commented Mar 15, 2013 at 12:43
4 Answers
Reset to default 3Here is Updated Jsfiddle Demo
Html:
<input type="hidden" value="10000" id="amount"/>
<input type="text" value="0" id="count"/>
<input type="button" value="Start" id="starter"/>
<input type="button" value="Stop" id="stopper"/>
<input type="button" value="reset" id="resetter"/>
Script:
<script type="text/javascript">
var amount=parseInt($('#amount').val());
var i = parseInt($('#count').val());
var tim;
function run(){
tim = setInterval(function(){
if(i>=amount){clearInterval(tim); return;}
$('#count').val(++i);
},100);
}
run();
$('#stopper').click(function(){
clearInterval(tim);
});
$('#resetter').click(function(){
clearInterval(tim);
i=0;
$('#count').val(i);
run();
});
$('#starter').click(function(){
clearInterval(tim);
run();
});
</script>
Use document ready:
$(document).ready(function() {
run();
});
You can reset the counter by assigning count
to 0.
<input id="resetCount" type="button" />
function reset() {
$('#count').val(0);
}
$("#resetCount").click(function() {
reset();
});
you can call a function in onload you can do there
like
<script>
run();
</script>
The run() function will call whenever the page is loading.
Just call your run method in document ready :
$(document).ready(function() {
run();
});