DEV Community

Telmo Goncalves
Telmo Goncalves

Posted on

Random colour with JavaScript

I've Tweet this a few days ago and it got a little attention from the community.

While you're here you might want to follow me on Twitter

Liquid error: internal


The main reason for writing this post is to explain why to use 16777215, looks kind of a random number and can be a little misleading.


Why 16777215?

If you're familiar with RGB (Red, Green, Blue), you know it's represented by a number from 0 to 255, an example of a colour using RGB would look like:

/* Same as #ffffff */
color: rgb(255, 255, 255);
Enter fullscreen mode Exit fullscreen mode

Now, if we do 256 * 256 * 256 we end up with 16,777,216, now why do we remove 1 from this value?

We want to convert into a hexadecimal format and 16777216 converts to 1000000, while 16777215 converts to ffffff.

I did a little research but mainly this came from here, thanks Jacob:


There are other explanations, based directly on the hexadecimal code, but I felt this one made more sense and it was simpler.


Happy to discuss this further and give me a shout if you think something's not right. I'm always open to learning something new. Connect on Twitter if you want to discuss.

Hope this makes sense to you 🔥

Top comments (8)

Collapse
 
savagepixie profile image
SavagePixie

Great explanation, but that method can generate hexadecimal numbers with less than six digits, so you might want to pad the start with zeroes.

Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0')
Collapse
 
telmo profile image
Telmo Goncalves

Thanks for that 🙏

Collapse
 
lexlohr profile image
Alex Lohr

You could also use (16777216 * (1 + Math.random()) | 0).toString(16).slice(1).

Collapse
 
alexnfsc175 profile image
alexnfsc175 • Edited

lets test this trick, in this page open chrome console and paste this code, and see the title change color:

for (var i=0;i<=10000;i++) {
   (function(ind) {
       setTimeout(function(){document.querySelector('#main-title > h1').style.color = `#${Math.floor(Math.random() * 16777215).toString(16).padStart(6,'0')}`;}, 1000 + (300 * ind));
   })(i);
}
Collapse
 
telmo profile image
Telmo Goncalves

Awesome 😆

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

parseInt('ffffff', 16) would be more straightforward and easy to refractor.

BTW, parseInt('ffffffff', 16) if you need alpha channel (opacity).

It seems that 0xFFFFFF also works.

Collapse
 
telmo profile image
Telmo Goncalves

Thanks 🙏

Collapse
 
faisalawanisee profile image
Faisal Awan

Nice article, Thanks @telmo