views:

179

answers:

1

Hi there.

Sorry if this is a vague question... I'm not really sure how to go about it so maybe someone with the wisdom can point me in the right direction :)

Basically, I want to create a function that will accept any old string (will usually be a single word) and from that somehow generate a hexadecimal value between #000000 and #FFFFFF, so I can use it as a colour for a HTML element.

Maybe even a shorthand hex value (i.e: #FFF) if that's less complicated. In fact, a colour from a 'web-safe' palette would be ideal.

I've had a look on the site and there were some similar questions for RoR and Java, but they didn't look too transferable. Having said that I'm not that familiar with the finer points of JavaScript.

Thanks and much appreciation in advance :) Darragh

+2  A: 

Just porting over the Java from http://stackoverflow.com/questions/2464745/compute-hex-color-code-for-an-arbitrary-string to Javascript:

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 intToARGB(i){
    return ((i>>24)&0xFF).toString(16) + 
           ((i>>16)&0xFF).toString(16) + 
           ((i>>8)&0xFF).toString(16) + 
           (i&0xFF).toString(16);
}

To convert you would do:

intToARGB(hashCode(your_string))

Although it yields some numbers with length greater than 6...

CD Sanchez
great! thanks, this works well. I don't know much about bitwise operators and stuff so your help porting it over is appreciated.
Darragh