Skip to content

Instantly share code, notes, and snippets.

@luqmaan
Created November 29, 2012 14:38
Show Gist options
  • Save luqmaan/4169492 to your computer and use it in GitHub Desktop.
Save luqmaan/4169492 to your computer and use it in GitHub Desktop.
Darkens or lightens a CSS RGB color.
/**
* Darkens or lightens a CSS RGB color. Derived from http://www.sitekickr.com/coda/jquery/darken-background-color-element.html
* @param {string} rgb "rgb(26,26,26)""
* @param {string} type "darken" or "lighten"
* @param {int} percent
* @return {string} returns the altered RGB color
*/
function alterColor(rgb, type, percent) {
rgb = rgb.replace('rgb(', '').replace(')', '').split(',');
var red = trim.call(rgb[0]);
var green = trim.call(rgb[1]);
var blue = trim.call(rgb[2]);
if(type === "darken") {
red = parseInt(red * (100 - percent) / 100, 10);
green = parseInt(green * (100 - percent) / 100, 10);
blue = parseInt(blue * (100 - percent) / 100, 10);
} else {
red = parseInt(red * (100 + percent) / 100, 10);
green = parseInt(green * (100 + percent) / 100, 10);
blue = parseInt(blue * (100 + percent) / 100, 10);
}
rgb = 'rgb(' + red + ', ' + green + ', ' + blue + ')';
return rgb;
}
/* You could use jQuery.trim() instead */
function trim(){return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');};
@alanfluff
Copy link

I found that the lighten option didn't work for me (perhaps it's what I was passing in or my jQ env'). Anyway, eventually found that oddly the darken maths worked but for lighten it got it wrong buy multiples, traced it down to needing percent to be cleaned on arrival, so I just added:

percent = parseInt(percent);

after the opening function alterColor line.

Thanks for the code BTW ^_^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment