DEV Community

Nicholas Fazzolari
Nicholas Fazzolari

Posted on • Updated on

Generate and Set Pseudorandom Hexadecimal Background Color Using JavaScript

I'm working on a project that deals with pseudo random event-driven color changes and needed a solution to generate hexadecimal codes for web use.

Program Design and Thinking:

I know that hexadecimal color codes represent red green and blue values in base 16. Which are defined by the following pattern:

Hexadecimal number explanation

I started thinking about what type and data structure to use in the implementation. I cam up with a general idea using a sets to define the base set and a general rule to build a six value hexadecimal color code.

  • Where H is the set of hex values - These will be defined as strings.
  • The set 'Hexadecimal Color Code' - uses +=, the operator from JavaScript to concatenate a range of values from H

General outline of how to build hex codes

At this point I was able to start writing some code. I will let the code speak for itself in the embed below.

Discussion and Insight:

As a Computer Science student and total nerd I have a question about this code.

  • Can these values be generated totally numerically, then parsed as strings after generation? I know in C/C++ (my coding comfort zone) you can do this. With my current knowledge of JavaScript I have yet to discover a method.

Any other insights or comments would be appreciated.

The Code

Taking it Further:

After I implemented this I started thinking about doing more complex and potentially useful things with hex colors. For example, one could build on this idea and implement the code in such a way that only the R, G, or B get generated or a certain combination of the three.

Anyways, I hope some discussion arises from this, and this post was interesting.

If you enjoyed this content and want to support a poor freelancing student so I can eat and produce more content in the future, I accept donations via PayPal

Top comments (19)

somedood profile image
Basti Ortiz • Edited

This is a great read for beginners. I also wondered how to make a random color generator before in my early days.

Also, you don't need to add an id to the <body> tag; you can directly refer to it by writing document.body. 😉

chiff profile image
Chiffre • Edited

TL;DR - you don't want to use that

@dood also every #ID is in DOM is accessible via window[id] however it's diacouraged to use that because it was implemnted in browsers due historic and compatibility reasons. More info here. It can be removed in future and make your page not working. Check answers and comments too. What I wanted to say is that window.body could be accessible because of same reason (I'm not sure).

somedood profile image
Basti Ortiz

Oh, wow. I never even knew that you could access an id from the window object. Thanks for making me learn something new today! I am genuinely surprised and amused by this.

nickfazzpdx profile image
Nicholas Fazzolari

Thanks for the heads up. Does using id's to link js to the DOM hurt performance (at scale)?

antjanus profile image
Antonin J. (they/them)

I saw a tweet about this last week! Using document.querySelector('body') is actually more performant than using document.body. So I wonder if doing document.querySelector('#some-id') would still be faster than document.body! :)

Thread Thread
somedood profile image
Basti Ortiz

I wonder if there's a jsPerf for that by now. I'm really curious to see which method is more performant.

somedood profile image
Basti Ortiz

Yes, it's definitely going to hurt performance at scale. Though you shouldn't worry about too much unless it's completely necessary to optimize and squeeze every single bit of efficiency for your CPU.

Optimization is good, but as soon as you allow it to become premature optimization, that's when you should reconsider your priorities. You wouldn't want to allow the latter to get in the way of making actual progress in software development.

jonrandy profile image
Jon Randy 🎖️ • Edited
randomHexColour = ()=>'#'+(~~(Math.random()*(2<<23))).toString(16).padStart(6,0);
nickfazzpdx profile image
Nicholas Fazzolari • Edited

This is awesome! Now I get to spend this afternoon understanding the code. Thank you.

stereobooster profile image
stereobooster • Edited
() => `#${Math.floor(Math.random()*(16777215 + 1)).toString(16).padStart(6,"0")}`
herrfugbaum profile image

A while ago I played around with something similar. I needed to generate a bunch of random colors but that always looked awful, so i ended up writing this little snippet:

/* @param alpha boolean
* if true a random value for the alpha channel is calculated, else alpha channel = 1 (full saturation)
var randomPastelColor = function (alpha) {
  var rndm = function (f) { return Math.floor(Math.random() * f)},
  pstlfy = function (p) { return Math.round((p + 255) / 2)},
  r = pstlfy(rndm(256)),
  g = pstlfy(rndm(256)),
  b = pstlfy(rndm(256)),
  a = alpha ? rndm(11) / 10 : 1

  return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')'
} (I didn't get the embedding working 😂)

It generates random pastel colors, which are easier on the eyes in my opinion. The trick to "pastelify" is to just take each individual value add 255 (or FF) and divide it by two ✨

webreflection profile image
Andrea Giammarchi • Edited
function generateRandomHexColor() {
  const rgb = () => ('0' + (Math.random() * 256).toString(16)).slice(-2);
  return `#${rgb()}${rgb()}${rgb()}`;
darkain profile image
Vincent Milum Jr

Have you considered using .toString(16)? Also, what about just using actual CSS integer RGB values instead of hex? Seems like either could simplify this. :)

craigmc08 profile image
Craig McIlwrath

toString(16) has the problem of numbers like 14 ending up being one character long, so you need a left pad function. rgb color values are the best solution, imo (or hsl)

dabrorius profile image
Filip Defar • Edited

Interesting problem! Here's my attempt of solving it in more functional programming style, without converting it into a convoluted one-liner.

Scratch that! There's a simpler implementation:

jonrandy profile image
Jon Randy 🎖️

Just noticed, your first image is wrong - it specifies the pattern as RBG, it should be RGB

nickfazzpdx profile image
Nicholas Fazzolari

Man! I proof read it and a major problem still slipped through. Thanks for the heads up. Fixing it up.

jwjcmw profile image
Jim Wright

Nice work! Just one thing...I think your max on the hexSeed needs to be 16 or you won't ever get an F.

nickfazzpdx profile image
Nicholas Fazzolari

Thanks for pointing that out.