<span class="background">Foo Fighter</span>

<div>
  <label for="color">background color:</label>
  <input type="color" id="color" name="color" value="#e66465" />
</div>
* {
  font-size: 2rem;
}

.background {
  height: 1.5rem;
  line-height: 1.5rem;
  background-color: #e66465; /* change me */
  padding: 0 10px;
}
window.onload = () => {
  const colorPicker = document.querySelector('#color');
  colorPicker.addEventListener('input', handleColorInput, false);
};

function handleColorInput(event) {
  changeBackgroundColor(event.target.value);
  adjustFontColor(event.target.value);
}

function changeBackgroundColor(color) {
  document.querySelector('.background').style.backgroundColor = color;
}

function adjustFontColor(backgroundColor) {
  const textColor = textColorBasedOnBackground(backgroundColor);

  document.querySelector('.background').style.color = textColor;

  console.log("background color: ", backgroundColor);
  console.log("text color: ", textColor);
}

// suppose background color is: rbg(0, 23, 255)
function textColorBasedOnBackground(backgroundColor) {
  backgroundColor = backgroundColor.substring(1);
  const r = parseInt(backgroundColor.substring(0,2), 16); // 0 ~ 255
  const g = parseInt(backgroundColor.substring(2,4), 16);
  const b = parseInt(backgroundColor.substring(4,6), 16);

  const srgb = [r / 255, g / 255, b / 255];
  const x = srgb.map((i) => {
    if (i <= 0.04045) {
      return i / 12.92;
    } else {
      return Math.pow((i + 0.055) / 1.055, 2.4);
    }
  });

  const L = 0.2126 * x[0] + 0.7152 * x[1] + 0.0722 * x[2];
  return L > 0.179 ? "#000" : "#fff";
}

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.