Skip to content

Instantly share code, notes, and snippets.

@renancouto
Created January 30, 2013 17:58
Show Gist options
  • Save renancouto/4675192 to your computer and use it in GitHub Desktop.
Save renancouto/4675192 to your computer and use it in GitHub Desktop.
Method to lighten / darken hex colors using Javascript.
var LightenColor = function(color, percent) {
var num = parseInt(color,16),
amt = Math.round(2.55 * percent),
R = (num >> 16) + amt,
B = (num >> 8 & 0x00FF) + amt,
G = (num & 0x0000FF) + amt;
return (0x1000000 + (R<255?R<1?0:R:255)*0x10000 + (B<255?B<1?0:B:255)*0x100 + (G<255?G<1?0:G:255)).toString(16).slice(1);
};
@rxluz
Copy link

rxluz commented Jun 7, 2018

Thank you!

@FelixGraf
Copy link

Thank you! ๐Ÿ‘
Add var num = parseInt(color.replace("#",""), 16), to be able to parse hex values containing the #

@suhailkc
Copy link

suhailkc commented Jul 21, 2019

Thank you ๐Ÿ‘๐Ÿ‘๐Ÿ‘๐Ÿ‘
worked after little changes.

var color = {
primary: "#4d8af0",
secondary: "#7987a1",
success: "#42b72a",
info: "#68afff",
warning: "#fbbc06",
danger: "#ff3366"
}

function LightenColor(color, percent) {
var num = parseInt(color.replace("#",""),16),
amt = Math.round(2.55 * percent),
R = (num >> 16) + amt,
B = (num >> 8 & 0x00FF) + amt,
G = (num & 0x0000FF) + amt;
return "#" + (0x1000000 + (R<255?R<1?0:R:255)*0x10000 + (B<255?B<1?0:B:255)*0x100 + (G<255?G<1?0:G:255)).toString(16).slice(1);
};

var a = color.primary;
var b = LightenColor(color.primary, 12);
var c = LightenColor(color.primary, 22);

@hiukky
Copy link

hiukky commented May 27, 2020

Very nice!

@jatinrane
Copy link

This is great. Thanks a lot.

Implemented the same in Angular here by using a dummy dataset:
https://stackblitz.com/edit/angular-ivy-rndlwi?file=src/app/app.component.ts

My requirement was to show different shades of a color based on the value in data. Red shades for Negative Values. Green Shades for Positive value.

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