Introduction
In this lab, we will be exploring how to change the lightness of an hsl() color string using JavaScript. By leveraging string manipulation, array methods, and mathematical functions, we will learn how to modify the lightness value while ensuring that it stays within the valid range of 0 to 100. This skill will come in handy when developing web applications that require dynamic color manipulations based on user interactions.
How to Change the Lightness of an HSL Color
To change the lightness value of an hsl() color string, follow these steps:
Open the Terminal/SSH and type
nodeto start practicing coding.Use
String.prototype.match()to get an array of three strings with the numeric values from thehsl()string.Use
Array.prototype.map()in combination withNumberto convert the strings into an array of numeric values.Ensure the lightness value falls within the valid range (between
0and100) usingMath.max()andMath.min().Use a template literal to create a new
hsl()string with the updated lightness value.
Here's an example code snippet that implements these steps:
const changeLightness = (delta, hslStr) => {
const [hue, saturation, lightness] = hslStr.match(/\d+/g).map(Number);
const newLightness = Math.max(
0,
Math.min(100, lightness + parseFloat(delta))
);
return `hsl(${hue}, ${saturation}%, ${newLightness}%)`;
};
You can then call the changeLightness() function with a delta value and an hsl() string to get a new hsl() string with the updated lightness value. For example:
changeLightness(10, "hsl(330, 50%, 50%)"); // 'hsl(330, 50%, 60%)'
changeLightness(-10, "hsl(330, 50%, 50%)"); // 'hsl(330, 50%, 40%)'
Summary
Congratulations! You have completed the Change Color Lightness lab. You can practice more labs in LabEx to improve your skills.