/* Color Fade Requires: jQuery 1.7.1+ (probably much lower) Description: Simple color animation. Fades one color into another on the selected element(s) Arguments: - target (array) The target color we are animating to as a 3 element array of integers [r,g,b] - duration (int) How long it should take to fade the colors (optional, default: 400) - callback (function) A callback function to be fired when fading is complete (optional, default: none) - property (string) The CSS property whose color we are fading (optional, default: backgroundColor) Usage: $( '#myelement' ).colorFade( [250,20,130] ); */ $.fn.colorFade = function( target, duration, callback, property ) { var methods = { /* Method to take a color input and check it and conform it to the format that we need Arguments: - color (string) The color we are checking */ conform_color : function( color ) { // If it's already array, no need to mess with it if ( typeof color === 'object' ) { return color; } if ( !color || typeof color !== 'string' || 'rgb(' !== color.substring( 0, 4 ) ) { color = 'rgb(255,255,255)'; } // Convert original color into array of number strings color = color.replace( /[^0-9,]/gi, '' ).split( ',' ); // Parse array of number strings into array of integers return $.map( color, function( str ) { return parseInt( str ); }); } }; // Set default property if none is specified if ( typeof property === 'undefined' || !property ) { property = 'backgroundColor'; } // Set default animation duration if none is specified if ( typeof duration === 'undefined' || !duration ) { duration = 400; } // Conform the target color to our specs target = methods.conform_color( target ); // Return 'this' to maintain chainability return this.each(function() { var $this = $(this), original = methods.conform_color( $this.css( property ) ); // Create a dummy element to animate so we can use a step function (don't insert element into DOM) $( '
' ).animate( { 'width' : 100 }, { duration : duration, easing : 'swing', // Fade the colors in the step function step : function( now, fx ) { var completion = ( now - fx.start ) / ( fx.end - fx.start ); $this.css( property, 'rgb(' + Math.round( original[0] + ( ( target[0] - original[0] ) * completion ) ) + ',' + Math.round( original[1] + ( ( target[1] - original[1] ) * completion ) ) + ',' + Math.round( original[2] + ( ( target[2] - original[2] ) * completion ) ) + ')' ); }, // Fire the callback if one was provided complete : function() { if ( typeof callback === 'function' ) { callback(); } } }); }); };