How to generate a random Hex Color Code in Javascript

A Hexadecimal color code looks like #ff7f00. This means:

  • red: ff hexadecimal = 255 decimal
  • green: 7f hexadecimal = 127 decimal
  • blue: 00 hexadecimal = 0 decimal

And that will generate a orange color with hex value ff7f00.

One can think of several very difficult methods to generate 3 numbers between 0 and 255, then concatenating their hexadecimal values. But there's a much easier way.

Since the string is formatted as a 6 character string, the value of which is between 000000 and ffffff (hex), you could just pick any random value between 0 and 16777215 (=hex ffffff) and convert that to a hex string.

Both of these lines will generate a random Hex Color Code:

'#' + Math.floor(Math.random()*0xffffff).toString(16);
'#' + Math.floor(Math.random()*16777215).toString(16);

Simple huh?

© GeekLabInfo How to generate a random Hex Color Code in Javascript is a post from GeekLab.info. You are free to copy materials from GeekLab.info, but you are required to link back to http://www.geeklab.info

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...
Categories: IT

Leave a Reply