Generate module colors from text

by core972

HTML

<div class="module-container">
  <div class="module">Minceur</div>
  <div class="module">Entrainement 2</div>
  <div class="module">Sommeil / Digestion</div>
  <div class="module">Bio 1</div>
  <div class="module">Vitalite</div>
</div>

CSS

.module-container{
  display: flex;
  flex-flow: row wrap;
}
.module {
  background-color: var(--bg-color);
  height: 3rem;
  width: 6.5rem;
  border-radius: 0.35rem;
  padding: 2rem;
  margin: 1rem;
  text-align: center;
  line-height: 1.2rem;
}

JavaScript

const stringToColour = (str) => {
  let hash = 0;
  str.split('').forEach(char => {
    hash = char.charCodeAt(0) + ((hash << 5) - hash);
  })
  let colour = '#';
  for (let i = 0; i < 3; i++) {
    let value = (hash >> (i * 8)) & 0xff;
    let out = value;
    if (value < 50) {
      out += 175;
    } else if (value < 150) {
      out += 75;
    }
    console.log(str, value, out);
    colour += out.toString(16).padStart(2, '0')
  }
  return colour;
}

const moduleList = document.querySelectorAll(".module");
moduleList.forEach(mod => {
  const bgColor = stringToColour(mod.innerText);
  mod.style.setProperty("--bg-color", bgColor);
})