# Convert Darker to Lighter or Vice versa

## #Function Code: Function Code:

```/* Helper function */
var pad = function(num, totalChars) {
num = num + '';
while (num.length < totalChars) {
}
return num;
};

// Ratio is between 0 and 1
var changeColor = function(color, ratio, darker) {
color = color.replace(/^s*|s*\$/, '');

// Expand three-digit hex
color = color.replace(
/^#?([a-f0-9])([a-f0-9])([a-f0-9])\$/i,
'#\$1\$1\$2\$2\$3\$3'
);

// Calculate ratio
var difference = Math.round(ratio * 256) * (darker ? -1 : 1),
// Determine if input is RGB(A)
rgb = color.match(new RegExp('^rgba?\(\s*' +
'(\d|[1-9]\d|1\d{2}|2[0-4][0-9]|25[0-5])' +
'\s*,\s*' +
'(\d|[1-9]\d|1\d{2}|2[0-4][0-9]|25[0-5])' +
'\s*,\s*' +
'(\d|[1-9]\d|1\d{2}|2[0-4][0-9]|25[0-5])' +
'(?:\s*,\s*' +
'(0|1|0?\.\d+))?' +
'\s*\)

Top ↑#How to use? How to use?

/*--------------------------------------------------------*/
var hex     = '#ffa039';
var rgb     = 'rgb(255, 153, 0)';
var rgba    = 'rgba(255, 153, 0, 0.3)';

//  Convert colors
//      Here .2 is ratio
var hex_light   = lighterColor( hex , .2);
var hex_dark    = darkerColor( hex , .2);

var rgb_light   = lighterColor( rgb , .2);
var rgb_dark    = darkerColor( rgb , .2);

var rgba_light  = lighterColor( rgba , .2);
var rgba_dark   = darkerColor( rgba , .2);

How to use?
Refer: http://jsfiddle.net/maheshwaghmare/25tsu1r5/3/
How ratio works?
Refer: http://jsfiddle.net/maheshwaghmare/85bqkwep/
, 'i')),
alpha = !!rgb && rgb[4] != null ? rgb[4] : null,
// Convert hex to decimal
decimal = !!rgb? [rgb[1], rgb[2], rgb[3]] : color.replace(
/^#?([a-f0-9][a-f0-9])([a-f0-9][a-f0-9])([a-f0-9][a-f0-9])/i,
function() {
return parseInt(arguments[1], 16) + ',' +
parseInt(arguments[2], 16) + ',' +
parseInt(arguments[3], 16);
}
).split(/,/),
returnValue;
// Return RGB(A)
return !!rgb ?
'rgb' + (alpha !== null ? 'a' : '') + '(' +
Math[darker ? 'max' : 'min'](
parseInt(decimal[0], 10) + difference, darker ? 0 : 255
) + ', ' +
Math[darker ? 'max' : 'min'](
parseInt(decimal[1], 10) + difference, darker ? 0 : 255
) + ', ' +
Math[darker ? 'max' : 'min'](
parseInt(decimal[2], 10) + difference, darker ? 0 : 255
) +
(alpha !== null ? ', ' + alpha : '') +
')' :
// Return hex
[
'#',
parseInt(decimal[0], 10) + difference, darker ? 0 : 255
).toString(16), 2),
parseInt(decimal[1], 10) + difference, darker ? 0 : 255
).toString(16), 2),
parseInt(decimal[2], 10) + difference, darker ? 0 : 255
).toString(16), 2)
].join('');
};
var lighterColor = function(color, ratio) {
return changeColor(color, ratio, false);
};
var darkerColor = function(color, ratio) {
return changeColor(color, ratio, true);
};
Top ↑#How to use? How to use?

How to use?
Refer: http://jsfiddle.net/maheshwaghmare/25tsu1r5/3/
How ratio works?
Refer: http://jsfiddle.net/maheshwaghmare/85bqkwep/