There have been various suggestions in the discussion regarding choosing between black and white text color depending on the background.
Many of these ideas have already been addressed in the comments. Let's break down each suggestion:
Using CSS mix-blend-mode - not a feasible option, as there isn't a single setting that guarantees legibility on all backgrounds.
Utilizing CSS (the preferred approach) - unfortunately, this is not possible because the div requiring dynamic text color based on the background is generated by JavaScript at runtime.
Employing JS - yes, it can be done. Since the div is created by JS and has its background-color set dynamically, setting the text color alongside is efficient.
The JS code mentioned in the question now includes a color setting:
'<div style="background-color:' + bgColor + '; color: ' + textBlackOrWhite(bgColor) + ';"'
Below is a code snippet defining the function for determining whether to use black or white text color based roughly on the brightness of the background. Refer to the related discussions on Stack Overflow for insights into human color perception complexities.
//function retrieved from https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
function textBlackOrWhite(hex) {
// Expanding shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);//also checks we have a well-formed hex number
//Function inspired by https://stackoverflow.com/questions/596216 provided by @FranciPenov for an approximation: (R+R+G+G+G+B)/6
let itsbright = function () { return ((2*parseInt(result[1], 16) + 3*parseInt(result[2], 16) + parseInt(result[3], 16))/6)>127; }
return result ? (itsbright()) ? '#000000' : '#ffffff' : '#000000';//defaults to black if bgColor wasn't a valid 3 or 6 digit hex color
}
<div id="div" style="font-family: monospace; box-sizing: border-box; margin: 0; padding: 40px 0; width: 100px; height: 100px; border-style: solid; border-radius: 50%; background-color: black; color: white;text-align:center;">#ffffff</div>
Click to select a background color: <input id="input" placeholder='#00000' type='color' value='#000000'/>
<button onclick="let d = document.getElementById('div'); let i = document.getElementById('input'); d.innerHTML = i.value; d.style.backgroundColor = i.value; d.style.color = textBlackOrWhite(i.value);">Submit</button>