Getting a random background color in javascript

function getRandomColor () {
  var hex = Math.floor(Math.random() * 0xFFFFFF);
  return "#" + ("000000" + hex.toString(16)).substr(-6);
}

hex.toString(16) converts hex into string number representation in base 16.

Syntax:

number.toString(radix)

radix: Base to use for representing a numeric value. Must be an integer between 2 and 36.

2 - The number will show as a binary value
8 - The number will show as an octal value
16 - The number will show as an hexadecimal value

substr(-6) just takes the last 6 characters, which cuts off the "000000" because they're not part of the last 6 characters.


hex.toString(16) converts hex into string number representation in base 16. Then it appends 000000 at the beginning of the string to make sure it will be at least of length 6. and substr(-6) takes last 6 chars of the resulting string. This way you always get # + 6 hex chars. Which represents color.

Tags:

Javascript