Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A very simple animation for numbers.
jQuery( document ).ready( function( $ ) {
$.fn.animate_number = function( options ) {
options.fromNumber = options.fromNumber ? options.fromNumber : 0;
options.toNumber = options.toNumber ? options.toNumber : 0;
options.rounding = options.rounding ? options.rounding : 0;
options.thousands = options.thousands ? options.thousands : '';
options.decimals = options.decimals ? options.decimals : '.';
options.element = this;
function format_number( value ) {
value = value.toString();
value = parseFloat( value ).toFixed( parseInt(options.rounding) );
value = value.split( '.' ).join( '#' );
var decimals_string = value.substring( (value.length - (options.rounding + 1)), value.length );
value = value.toString().replace( /\B(?=(\d{3})+(?!\d))/g, options.thousands );
value = value.split( decimals_string ).join( '' );
decimals_string = decimals_string.split( '#' ).join( options.decimals );
value = value + decimals_string;
if ( options.append )
value = value + options.append
if ( options.prepend )
value = options.prepend + value
return value;
}
$( { someValue: options.fromNumber} ).animate( { someValue: options.toNumber }, {
duration: options.duration ? options.duration : 3000,
easing: options.easing ? options.easing : 'linear',
step: function() { /* called on every step */
$( options.element ).text( format_number( this.someValue ) );
},
complete: function() {
$( options.element ).text( format_number( options.toNumber ) );
}
});
}
});
/*$('#el').animate_number( { fromNumber: '1200.00', toNumber: '3900.99', rounding: 2, thousands: '.', decimals: ',', append: '%', prepend: '$', duration: 5000, easing: 'swing' } );*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment