Skip to content

Instantly share code, notes, and snippets.

@sagar-gavhane
Last active October 8, 2019 06:14
Show Gist options
  • Save sagar-gavhane/434f979e7ff81a9c5fb7c7bc4a78456c to your computer and use it in GitHub Desktop.
Save sagar-gavhane/434f979e7ff81a9c5fb7c7bc4a78456c to your computer and use it in GitHub Desktop.
Creating Avatars With Colors Using The Modulus. Ref: https://dev.to/marcoslooten/creating-avatars-with-colors-using-the-modulus-41g7
<div class="avatar">OP</div>
.avatar {
  width: 52px;
  height: 52px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ccc;
  border-radius: 50%;
  font-family: sans-serif;
  color: #fff;
  font-weight: bold;
  font-size: 16px;
}
const colors = ["#00AA55", "#009FD4", "#B381B3", "#939393", "#E3BC00", "#D47500", "#DC2A2A"];

function numberFromText(text) { // numberFromText("AA");
  const charCodes = text
    .split('') // => ["A", "A"] 
    .map(char => char.charCodeAt(0)) // => [65, 65]
    .join(''); // => "6565"
  return parseInt(charCodes, 10);
};

const avatars = document.querySelectorAll('.avatar');

avatars.forEach(avatar => {
  const text = avatar.innerText; // => "AA"
  avatar.style.backgroundColor = colors[numberFromText(text) % colors.length]; // => "#DC2A2A"
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment