This is a very old question I run into, but I didn’t like any of the answers so I’m providing mine:
To get a favorable text color you can check the background color's luminance and return either black or white color for the text.
See the function GetLumColor() below in this demo code which is the crux of the answer to the question.
<!DOCTYPE html><head></head>
<body onload="Test();">
<script type="text/javascript">
//--------------------------------------------------------------------------------
function RandomNum(Num){return Math.floor(Math.random()*Num);}
//--------------------------------------------------------------------------------
// NB: accepts rgb() or rgba() color values but the alpha-channel is not taken into consideration
function GetLumColor(Rgb){
Rgb=Rgb.replace(/ /g,'').replace('rgba(','').replace('rgb(','').replace(')','').split(',');
let R=Number(Rgb[0]), G=Number(Rgb[1]), B=Number(Rgb[2]), Color='black';
let Lum=((R+G+B)*100)/765; // luminance as a percentage
if(Lum<50){Color='white';} // adjust this number to suit
return Color;}
//--------------------------------------------------------------------------------
// Tests the function above
function Test(){
var S='', Bg='', Fg='';
for(let i=0; i<40; i++){
Bg='rgb('+RandomNum(256)+','+RandomNum(256)+','+RandomNum(256)+')';
Fg=GetLumColor(Bg);
S+='<div style="background:'+Bg+'; color:'+Fg+';"> Sample 123 </div>';
}
document.write(S);
}
//--------------------------------------------------------------------------------
</script></body></html>
Basic usage...
some_ID.style.color = GetLumColor(some_ID.style.background);