convert Text to Color

by Anov Siradj

HTML

<input value="anovsiradj">

<!--
https://stackoverflow.com/questions/21646738/convert-hex-to-rgba
https://stackoverflow.com/questions/3426404/create-a-hexadecimal-colour-based-on-a-string-with-javascript
-->

JavaScript

(() => {
  var input = document.querySelector('input');
  var output = document.body;

  input.addEventListener('input', function(ev) {
    colorify(this.value);
  });
  input.dispatchEvent(new Event('input'));

  function colorify(texts) {
    output.style.backgroundColor = '#' + intToARGB(hashCode(texts));
  }

  function hashCode(str) { // java String#hashCode
    var hash = 0,
      i;
    for (i = 0; i < str.length; i++) {
      hash = str.charCodeAt(i) + ((hash << 5) - hash);
    }
    return hash;
  }

  function intToARGB(i) {
    return ((i >> 24) & 0xFF).toString(16) +
      ((i >> 16) & 0xFF).toString(16) +
      ((i >> 8) & 0xFF).toString(16) +
      (i & 0xFF).toString(16);
  }
})();