Skip to content

Instantly share code, notes, and snippets.

@luis-almeida
Created June 15, 2012 01:07
Show Gist options
  • Save luis-almeida/2934007 to your computer and use it in GitHub Desktop.
Save luis-almeida/2934007 to your computer and use it in GitHub Desktop.
Extending jQuery with a function that returns a gradient color based on a hex
/*
* Usage:
* '#' is optional
* $.gradient( "#CCCCCC", -0.1 ); // returns a 10% darker hex color
* $.gradient( "#AAAAAA", 0.4 ); // returns a 40% lighter hex color
* $.gradient( "NTAF2S", 0.3 ); // returns false
*/
$.gradient = function ( hex, opacity ) {
if ( !/^#?[0-9a-f]{3,6}$/i.test( hex ) ) return false;
hex = hex.length < 6 ? hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2] : hex;
opacity = opacity || 0;
var rgb = "", c, i;
for ( i = 0; i < 3; i++ ) {
c = parseInt( hex.substr( i * 2, 2 ), 16 );
c = Math.round( Math.min( Math.max( 0, c + ( c * opacity ) ), 255 ) ).toString( 16 );
rgb += ( "00" + c ).substr( c.length );
};
return rgb;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment