vsupalov

Generate a random HTML color

October 29, 2011 [ javascript | old ]

This function returns a random HTML color string. It uses theĀ randomRange function to generate the numerical value.

function randomColor() {
  var s = "#";	

  for (var i = 0; i < 6; i++) {
    s+= randomRange(0,15).toString(16);
  }

  return s;
}

The value range of HTML colors starts at 0 and ends with (hex)ffffff, which is equal to 16777215 in the decimal system. The following method uses less Math.random() calls:

function randomColor() {
  var s = "#";
  var numberPart = randomRange(0,16777215).toString(16);

  while ((numberPart.length + s.length) < 7) { // insert leading '0's
    s+='0';
  }

  return s+numberPart;
}

Want to be notified when I publish new content?

Just enter your name and email below. You will also get content that I share exclusively with the list. Zero spam!