Generate and Set Pseudorandom Hexadecimal Background Color Using JavaScript

Nicholas Fazzolari on December 22, 2018

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. ... [Read Full]
markdown guide

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. 😉


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).


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.


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


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! :)

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


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.

randomHexColour = ()=>'#'+(~~(Math.random()*(2<<23))).toString(16).padStart(6,0);

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

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

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 + ')'

gist.github.com/herrfugbaum/7a6530... (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 ✨


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. :)


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)

function generateRandomHexColor() {
  const rgb = () => ('0' + (Math.random() * 256).toString(16)).slice(-2);
  return `#${rgb()}${rgb()}${rgb()}`;

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

Scratch that! There's a simpler implementation: codepen.io/dabrorius/pen/xNyJMO


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


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


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

code of conduct - report abuse