Created
November 29, 2012 14:38
-
-
Save luqmaan/4169492 to your computer and use it in GitHub Desktop.
Darkens or lightens a CSS RGB color.
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
/** | |
* 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*$/, '');}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:after the opening
function alterColor
line.Thanks for the code BTW ^_^