Last active
January 17, 2021 03:28
-
-
Save Durafen/a1d924f8498a5b2620a72fbd8d9c13b7 to your computer and use it in GitHub Desktop.
Generate unique color code based on string input [JS]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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