Reputation: 731
I need to "animate" a variable with jquery.
Example: The variable value is 1. The value should be 10 after 5 seconds. It should be increase "smoothly".
Hope that you know what I mean.
Thank you!
Upvotes: 16
Views: 20493
Reputation: 307
Try this:
var varToAnimate = 1;
$(window).animate({
varToAnimate: 10
}, 5000);
Note: This only works if the variable was set with var varToAnimate
or window.varToAnimate
.
When you set a variable, it creates a property in the window object. jQuery.animate()
animates properties, so $(window)
gets the window object, and varToAnimate: 10
animates the window's varToAnimate property to 10.
Upvotes: 0
Reputation: 221
As addition to Ties answer - you dont event need to append dummy element to the DOM. I do it like this:
$.fn.animateValueTo = function (value) {
var that = this;
$('<span>')
.css('display', 'none')
.css('letter-spacing', parseInt(that.text()))
.animate({ letterSpacing: value }, {
duration: 1000,
step: function (i) {
that.text(parseInt(i));
}
});
return this;
};
Upvotes: 0
Reputation: 675
This should work for you:
var a = 1;
var b = setInterval(function() {
console.log(a);
a++;
if (a == 10) { clearInterval(b); }
}, 500);
Upvotes: 2
Reputation: 5846
What you require is the step parameter in the $().animate
function.
var a = 1;
jQuery('#dummy').animate({ /* animate dummy value */},{
duration: 5000,
step: function(now,fx){
a = 1 + ((now/100)*9);
}
});
Upvotes: 13
Reputation: 100175
try:
$({someValue: 0}).animate({someValue: 10}, {
duration: 5000,
step: function() {
$('#el').text(Math.ceil(this.someValue));
}
});
<div id="el"></div>
Upvotes: 25
Reputation: 639
Html mark up as
Html
<span id="changeNumber">1</span>
You can change its value after 5 seconds.
JQuery:
setInterval(function() {
$('#changeNumber').text('10');
},5000);
Here is a Demo http://jsfiddle.net/Simplybj/Fbhs9/
Upvotes: 0
Reputation: 58521
increment with setTimeout
x = 1
for(i=0;i<1000;i+=100){
setTimeout(function(){
console.log(x++)
},i)
}
Upvotes: -1
Reputation: 9691
Use setInterval :
percentage = 0;
startValue = 1;
finishValue = 5;
currentValue = 1;
interval = setInterval(function(){
percentage ++;
currentValue = startValue + ((finishValue - startValue) * percentage) / 100;
doSomething(currentValue);
if (percentage == 100) clearInterval(interval);
}, duration / 100)
function doSomething(val) { /*process value*/}
Upvotes: 0