DEV Community

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

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

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

Collapse
 
nickfazzpdx profile image
Nicholas Fazzolari

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

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

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

Collapse
 
herrfugbaum profile image
Pascal

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 ✨

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

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

Collapse
 
stereobooster profile image
stereobooster • Edited
() => `#${Math.floor(Math.random()*(16777215 + 1)).toString(16).padStart(6,"0")}`
Collapse
 
webreflection profile image
Andrea Giammarchi • Edited
function generateRandomHexColor() {
  const rgb = () => ('0' + (Math.random() * 256).toString(16)).slice(-2);
  return `#${rgb()}${rgb()}${rgb()}`;
}
Collapse
 
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. :)

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

Collapse
 
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. codepen.io/dabrorius/pen/MdPXxB

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

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

Collapse
 
nickfazzpdx profile image
Nicholas Fazzolari

Thanks for pointing that out.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

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

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