DEV Community

Jack
Jack

Posted on

Give your users some colour

This is a real quick one!

If you have a project that involves users interacting with each other, like a chat app or something with profiles, it might be nice to assign them a colour. A bit like WhatsApp names. The challenge is how to make sure the same users always have the same colour as themselves, but within a wide range such that it's effectively random?

You can use ASCII key codes and the modulo operator and combine with HSL for a quick solution that will always return a random, but identical, hue, thereby converting any string into colour.


const name = 'Michael Jordan';
const characters = name.split('');
const code = characters.map(a => a.charCodeAt(0)).join('');
// code is 771059910497101108327411111410097110
const hue = code % 255;
const nameHSL = `hsl(${hue}, 80%, 40%)`;

Enter fullscreen mode Exit fullscreen mode

Of course, you might prefer to use a UID or 'user created at' timestamp in case you have two Michael Jordans - this works for literally any string!

For anyone wondering, MJ is this leafy green.

Screenshot 2021-04-13 at 18.14.15

Lovely.

Top comments (5)

Collapse
 
link2twenty profile image
Andrew Bone

Very interesting, I've made a quick fiddle of it πŸ˜…

Collapse
 
jackherizsmith profile image
Jack

I love this!

Collapse
 
therickedge profile image
Rithik Samanthula

I loved the blog and great work on the Fiddle man!

Collapse
 
seiyria profile image
Kyle J. Kemp

Interesting, both my name (kyle) and alias (seiyria) are the same color (#1458b8) - the green is off by a little bit but they're still really close!

Collapse
 
jackherizsmith profile image
Jack

!!

It would be interesting to crunch lots of names / random strings and see if this actually is nicely random, or it skews to certain colours. Instinctively I wonder if 255 is too round a number and if a prime might be better, but I'm not smart enough to work that one out.