Skip to main content

Archive

Show more

How To Generate a Random Color in JavaScript

how-to-generate-random-color-in-javascript


Question: How To Generate a Random Color in JavaScript

Answer:

Here we will show you three methods that will help you to generate random 'hexadecimal color code'.

First: using hexa decimal number concept.

  const randomColor = Math.floor(Math.random()*16777215).toString(16);
  document.body.style.backgroundColor = "#" + randomColor; //'16777215' is equal to 'ffffff' in decimal


Second: This method is our favorite because it's easy to make. The 'ternary operator' is used very well

var randomColor = (function generateColor(colorCode){   return (colorCode +=
  [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'][Math.floor(Math.random()*16)])  && (colorCode.length == 6) ?  colorCode : generateColor(colorCode); })('');

  document.body.style.backgroundColor = "#" + randomColor;
  


Third:

document.body.style.backgroundColor = (function (m, s, c) {
  return (c ? arguments.callee(m, s, c - 1) : '#') + s[m.floor(m.random() * s.length)]
})(Math, '0123456789ABCDEF', 5);


We try to provide you the best content, if there is any mistake in this article or there is any mistake in code, then let us know.

Comments