Skip to content

Instantly share code, notes, and snippets.

@Durafen
Last active January 17, 2021 03:28
Show Gist options
  • Save Durafen/a1d924f8498a5b2620a72fbd8d9c13b7 to your computer and use it in GitHub Desktop.
Save Durafen/a1d924f8498a5b2620a72fbd8d9c13b7 to your computer and use it in GitHub Desktop.
Generate unique color code based on string input [JS]
var stringToColour = function(str) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
var colour = '#';
for (var i = 0; i < 3; i++) {
var value = (hash >> (i * 8)) & 0xFF;
colour += ('00' + value.toString(16)).substr(-2);
}
return colour;
}
var text = prompt("Please enter text");
document.write(stringToColour(text))
$('body').css('background-color', stringToColour(text));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment