Lighten or Darken Hex Color in JavaScript
- 2 minutes read
Sometimes we need to programatically lighten or darken a given hex color in JavaScript.
The following snippet does just that:
const newShade = (hexColor, magnitude) => {
hexColor = hexColor.replace(`#`, ``);
if (hexColor.length === 6) {
const decimalColor = parseInt(hexColor, 16);
let r = (decimalColor >> 16) + magnitude;
r > 255 && (r = 255);
r < 0 && (r = 0);
let g = (decimalColor & 0x0000ff) + magnitude;
g > 255 && (g = 255);
g < 0 && (g = 0);
let b = ((decimalColor >> 8) & 0x00ff) + magnitude;
b > 255 && (b = 255);
b < 0 && (b = 0);
return `#${(g | (b << 8) | (r << 16)).toString(16)}`;
} else {
return hexColor;
}
};
This newShade
function accepts two parameters: hexColor
and magnitude
.
The hexColor
parameter is the hex color to lighten or darken. It doesn’t need to be preceded by a hashtag, but it can be. However, all hex values must be exactly six letters in length.
For example, #ffffff
and ffffff
are valid first parameters, but #fff
is an invalid value for hexColor
.
The other parameter, magnitude
, is an integer value which represents the magnitude by which hexColor
should be lightened or darkened.
We can lighten a color using newShade
by passing in a positive value for magnitude
:
const lighterColor = newShade(`#000000`, 50); // Returns "#323232"
And by passing in a negative integer, we can darken the given color:
const lighterColor = newShade(`#ffffff`, -50); // Returns "#cdcdcd"
Conclusion
I hope you found this snippet useful!
Working with bitwise operators in JavaScript can be a bit of a challenge, but there is a useful operator lookup tool that you can use as a reference.