Reputation: 859
I've browsed for hours and still can't find something worthy.
I want to animate a value of a text field from 0 to it's value. For example i'm having a textinput with value="100" and after any event or page load i want this value to animate from 0 to 100 (the starting value of input)
How could i do this? Thanks a lot in advance!
Upvotes: 0
Views: 2721
Reputation: 4936
You can use the 'step' option for the 'animate' function of jQuery to perform an action on each 'step' of the animation.
//When the document is ready..
jQuery(document).ready(function () {
//..loop over all of the INPUT elements that have a non-blank data-value field..
jQuery("input[data-value!='']").each(function (inputKey, inputItem) {
//..animate between the current value of the input (i.e. 0) and the desired
// value specified in the data-value field, setting to the full value upon
// completion of the animation
jQuery({
value: jQuery(inputItem).val()
}).animate({
value: jQuery(inputItem).data("value")
}, {
step: function () {
jQuery(inputItem).val(Math.round(this.value));
},
complete: function() {
jQuery(inputItem).val(jQuery(inputItem).data("value"));
}
});
});
});
Check out this jsFiddle example: http://jsfiddle.net/yE86J/9/1
I'd recommend using rounding to ensure you end up References: http://www.josscrowcroft.com/2011/code/jquery-animate-increment-decrement-numeric-text-elements-value/, jQuery how to find an element based on a data-attribute value?
Upvotes: 3
Reputation: 741
Try
$(document).ready(function(){
increase( $('#i') );
});
function increase( i , v ){
// let's store the initial/original input's value
if( !i.data.originalValue ) i.data.originalValue = i.val();
var currentVal = v || 0;
i.val(currentVal);
// if current value == initial/original value, then break the script
if( i.val() == i.data.originalValue ) {
alert( 'Complete!' ); // <-- callback here
return;
}
currentVal++;
// call this function again after 30ms
setTimeout( increase , 30 , i , currentVal );
}
Here is a fiddle example
Upvotes: 0