How to: Convert a String to Hex Colour (with JS)
· 395 wordsFor this site, when you hover over the Designed by a Turtle logo a colour is shown – which changes through out the site but isn’t random using JavaScript (I’ve updated the site since this post).
On a previous theme for Designed by a Turtle, a colour was picked based on the document title. That meant you could refresh the page and the colour would stay the same – but each page had a unique random colour. This was done by taking a constant to that page and converting it into the 6 digit hexadecimal value and using that as a colour. In this instance the page title was used as the input as it changed from page to page by using the document.title
variable.
Converting any string into a hexadecimal colour is achieved in two steps, first the string is hashed into a single large int representing the string (for example ‘Hello World’ would be -862545276). This integer is then converted into an RBG hex value by using the JavaScript toString(16)
method and as an extra check making sure the string does not exceed six characters by only returning those six characters.
The final step is to simply use this hex colour as you wish.
// Hash any string into an integer value
// Then we'll use the int and convert to hex.
function hashCode(str) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
return hash;
}
// Convert an int to hexadecimal with a max length
// of six characters.
function intToARGB(i) {
var hex = ((i>>24)&0xFF).toString(16) +
((i>>16)&0xFF).toString(16) +
((i>>8)&0xFF).toString(16) +
(i&0xFF).toString(16);
// Sometimes the string returned will be too short so we
// add zeros to pad it out, which later get removed if
// the length is greater than six.
hex += '000000';
return hex.substring(0, 6);
}
// Extend the string type to allow converting to hex for quick access.
String.prototype.toHexColour = function() {
return intToARGB(hashCode(this));
}
// Setup our demo.
window.onload = function() {
var stringInput = document.getElementById('string-input');
stringInput.addEventListener('input', function () {
// To use:
// Either directly call: intToARGB(hashCode( string ))
// or use the prototype method: string.toHexColour()
var colour = stringInput.value.toHexColour();
document.getElementById('colour-string').innerHTML = '#'+colour;
document.getElementById('colour-box').style.background = '#'+colour;
});
};
This was based on a StackOverflow answer by Cristian Sanchez.