DEV Community

Cover image for Generate unique color code in javascript
Rajnish Katharotiya
Rajnish Katharotiya

Posted on

Generate unique color code in javascript

Photo by Alice Dietrich on Unsplash

One fantastic way to make something alive is to fill it up with color. 😍

Well, the browser understands colors in the type call hex code ( it's one of them ). And choosing one is a little hard so what if you have some function that builds that code for you every time.

Before going further, Welcome to you all in a series of JavaScript Useful Snippet series, where I'm sharing sort codes to make development faster and efficient. If you haven't checked the previous episode go to profile and check now ( hit follow too ) otherwise stay tuned till the end πŸ˜ƒ ...

getMyColor()

When you need a unique hax-code on app loads or any functions call, getMyColor() will work like a charm. It's so simple to use, we need to just call it once and it'll return hex code right on. Well, let me show you what function does...

const getMyColor = () => {
  let n = (Math.random() * 0xfffff * 1000000).toString(16);
  return '#' + n.slice(0, 6);
};

In the first line, it's creating a random hex value by using the toString method of javascript. This function is use to convert a string into any format like binary, octal and hexadecimal. So, here I've used it for hexadecimal by passing 16 as an argument. And then once I got random values, I'm slicing 6 characters from it and concatenate with "#" on front. Boom we got hax code created. ( in generating hax code I've used "0xfffff" which is just represent the hexadecimal value )

Result will be like:

getMyColor()  // output: #59dfd0

One good use case I did recently with it is, I've set it to an element of DOM to make it random colored, it was fun. Try for yourself.

Let me know other possible use cases in a comment. hope this will help you, yes? then hit follow πŸ˜‚

Top comments (1)

Collapse
 
joaovmvini profile image
joaovmvini

Nice article, thanks for sharing! I have build a color-picker using vanilla JS, check it out: jsuites.net/v3/color-picker