string to random color

by Laurens Maneschijn

HTML

type/paste random string below to get a random color code:<br>
<textarea></textarea>

<div style="float: right;">
related links:
<ul>
<li><a href="https://stackoverflow.com/questions/3426404/create-a-hexadecimal-colour-based-on-a-string-with-javascript">1</a></li>
<li><a href="https://stackoverflow.com/questions/35969656/how-can-i-generate-the-opposite-color-according-to-current-color">2</a></li>
</ul>
</div>

<hr>

<div id="target"></div>

JavaScript

var ta = document.querySelector('textarea');
//ta.addEventListener('input', function(e){
$(document.body).on('input', 'textarea', function(e){
	var str, c, c_inverted;
	str = ta.value;
	
//	c = stringToColour(str);                // slow color increment
//	c = stringToColour2(str);               // slow color increment
//	c = '#' + intToRGB(hashCode(str));      // slow color increment
//	c = stringToColour3(str);               // slow color increment
//	c = StringToColor.next(str);            // this has a nice colour spread, 'aaa' and 'aab' get very different colors
	c = colorize(str);                      // good color spread, very tiny function.
	console.log(c);
//	c_inverted = '#' + invertHex(c.substr(1)); // ok ish invert, but colors inverted near middle gray #808080 are almost the same
//	c_inverted = invertColor(c); // ok ish invert, but colors inverted near middle gray #808080 are almost the same
	c_inverted = invertColor_bw(c, true); // either white or black, as long as clear to read on given color.
	var $div = $('<div>').text('color: ' + c + ' inverted: ' + c_inverted + ' : ' + str);
	$div.css('background-color', c).css('color', c_inverted);
	$('#target').prepend( $div );
});


//	////////////////////////////////////////////////////////////

// https://stackoverflow.com/a/3426956/1158769
// this one gradually changes to next color with each right-most char code increase. (so "aaa" and "aab" are almost the same color)

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

function intToRGB(i){
    var c = (i & 0x00FFFFFF)
        .toString(16)
        .toUpperCase();

    return "00000".substring(0, 6 - c.length) + c;
}


//	////////////////////////////////////////////////////////////

// source: https://stackoverflow.com/a/16348977/1158769
// source: http://jsfiddle.net/sUK45/
// this one gradually changes to next...