JSFiddle - React, Tailwind, and code Playground

by Simon Price

HTML

<div id="colorfulDiv">#ffffff</div>

CSS

#colorfulDiv {
    /* Additional styling as needed */
    text-align: center;
    width: 200px;
}

JavaScript

function updateDivColorAndTextColor(divId) {
    var div = document.getElementById(divId);
    var hexColor = div.innerText.trim();

    // Set the background color to the hex value
    div.style.backgroundColor = hexColor;

    // Convert hex color to RGB
    var rgb = hexToRgb(hexColor);

    // Calculate brightness
    var brightness = (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;

    // Set text color based on brightness
    div.style.color = brightness > 128 ? 'black' : 'white';
}

function hexToRgb(hex) {
    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;
    });

    var 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;
}

// Call the function to set colors
updateDivColorAndTextColor('colorfulDiv');