I have a list of names, which are usually updating from sql, in html5 , is it possible to make same names same color with javascript or jquery...
I tried to convert string to hex but I could not convert its to color code.
Regards...
I have a list of names, which are usually updating from sql, in html5 , is it possible to make same names same color with javascript or jquery...
I tried to convert string to hex but I could not convert its to color code.
Regards...
Here's how I'd do it.
Create a function that takes a name and spits out a random color, however it's not truly random as it uses the name to create the color, and as such it will always return the same color for the same name:
function nameToColor(name) {
var n = 'abcdefghijklmnopqrstuvwxyz'.split('');
var r = name.split('').map(function(e) {return n.indexOf(e);}).join('');
var l = parseFloat( '0.'+ (r*r*1000).toString().replace(/^0/, ''));
return '#'+Math.floor(l*16777215).toString(16);
}
OK, assuming you don't have any specific colours I have done this using a random colour generator function.
What you can do is loop your list of names, and for each new name store a new colour values in a dictionary. You can then check this dictionary for names you have already used and get that same colour.
For example:
Assuming your html is simply as follows:
<ul></ul>
You can use this javascript:
var names = [
"Bill", "Joe", "Oliver", "Joe", "George", "Bill", "George", "John"];
var currentAssignments = {};
for (var i = 0; i < names.length; i++) {
var name = names[i];
var colour = currentAssignments[name];
if (!colour) {
colour = GetRandomColour();
currentAssignments[name] = colour;
}
var li = $("<li>").html(name).css("color", colour);
$("ul").append(li);
}
function GetRandomColour() {
return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
Alternatively, if you have a predefined array of colours (and assuming you are sure you have enough unique colours to cater for all names) you could do this:
var colours = ["#F00", "#0F0", "#00F"];
and replace the GetRandomColour()
function as follows:
function GetRandomColour() {
return colours.pop();
}