I have some color swatches that should show the rgb value of the color displayed, with the background being the actual color. Then, if the color in question is light-ish, the text should be black, and if the color in question is dark-ish, the text color should be white.
How can I detect if the RGB value is light-ish or dark-ish??
<style>
#preview {
display: block;
height: 40px;
line-height: 40px;
font-size: 20px;
vertical-align: middle;
width: 150px;
text-align: center;
}
</style>
<!-- html -->
<button id="new_color">Try Random Color</button>
<p id="preview">Click the button!</p>
<script>
const getRandNum = () => Math.floor(Math.random() * 256);
const get_random_color = () => (`rgb(${getRandNum()}, ${getRandNum()}, ${getRandNum()})`);
const checkColor = (color) => {
// color = 'rgb(x, y, z)';
// check color is light
// or color is dark
return true;
}
$('#new_color').click(function(){
const p = $('#preview');
const bg_color = get_random_color();
const color_is_light = checkColor( bg_color );
const text_color = color_is_light ? 'black' : 'white';
p.css({
color: text_color,
backgroundColor: bg_color
})
});
</script>
I only found solutions for #hex colors, but not for rgb. Any help is very much appreciated.