<div class="container">
<div class="inputcont">
<label for="color">Enter color:</label>
<input type="color" name="color" id="color">
</div>
<div class="outputcont">
<label for="output" id="lightnesslabel">Lightness: </label>
<span id='output'>0.000</span>
</div>
</div>
* {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}
.container {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.inputcont {
margin: 1em;
display: flex;
align-items: flex-end;
height: 6em;
}
.outputcont {
margin: 1em;
display: flex;
align-items: flex-end;
height: 6em;
}
label {
font-weight: bold;
margin-right: 1em;
}
#color {
height: 6em;
width: 10em;
}
const colorInput = document.getElementById("color");
const output = document.getElementById("output");
colorInput.addEventListener("input", onInputChange);
function hexToRgb(h) {
var r = parseInt(cutHex(h).substring(0, 2), 16),
g = parseInt(cutHex(h).substring(2, 4), 16),
b = parseInt(cutHex(h).substring(4, 6), 16);
return "rgb(" + r + "," + g + "," + b + ")";
}
function cutHex(h) {
return h.charAt(0) == "#" ? h.substring(1, 7) : h;
}
function onInputChange(e) {
output.textContent = getLightnessOfRGB(hexToRgb(e.target.value)).toFixed(4);
}
function getLightnessOfRGB(rgbString) {
// First convert to an array of integers by removing the whitespace, taking the 3rd char to the 2nd last then splitting by ','
const rgbIntArray = rgbString
.replace(/ /g, "")
.slice(4, -1)
.split(",")
.map((e) => parseInt(e));
// Get the highest and lowest out of red green and blue
const highest = Math.max(...rgbIntArray);
const lowest = Math.min(...rgbIntArray);
// Return the average divided by 255
return (highest + lowest) / 2 / 255;
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.