JSFiddle - React, Tailwind, and code Playground
Perceived Brightness
by nilloc
HTML
<input id="picker" type="color">
<span>Perceived brightness: <span id="result"></span></span>
CSS
#result{
padding:6px;
border-radius:3px;
}
JavaScript
function hexToRgb(hex) {
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
$('input#picker').on('change', function() {
let textBrightness;
$('#result').html(
(function(c) {
textBrightness = Math.round(Math.sqrt( 0.299*c.r*c.r + 0.587*c.g*c.g + 0.114*c.b*c.b ))
return textBrightness;
})(hexToRgb($(this).val()))
).css("color", $(this).val()).css("background-color", (textBrightness > 165) ? '#555' : '#fff');
});