random color function js code example

Example 1: javascript random color generator

function generateRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

var randomColor=generateRandomColor();//"#F10531"

Example 2: random color code javascript

var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);
//generates a random color -> #56eec7

Example 3: random color in javascript

var randomColor = Math.floor(Math.random()*16777215).toString(16);

Example 4: javascript generate random color

const setBg = () => {
  const randomColor = Math.floor(Math.random()*16777215).toString(16);
  document.body.style.backgroundColor = "#" + randomColor;
  color.innerHTML = "#" + randomColor;
}

genNew.addEventListener("click", setBg);
setBg();