Created
June 15, 2012 01:07
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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