DEV Community

Jack
Jack

Posted on

7 1

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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay