Javascript Math Random Color via Hash value

Description

Javascript Math Random Color via Hash value

View in separate window

<!DOCTYPE html>
<head>
<title>Recipe</title>
<style>
#num//  w w  w. j a  v  a 2 s  .  c om
{
   height: 100px;
   width: 100px;
   background-color: #000000;
}
</style>
<script>

window.onload=function() {
  document.onclick=ranNumber;
}

function randomVal(val) {
  return Math.floor(Math.random() * val);
}

function randomColor() {
   // get red
   let r = randomVal(255).toString(16);
   if (r.length < 2) r= "0" + r;

   // get green
   let g = randomVal(255).toString(16);
   if (g.length < 2) g= "0" + g;

   // get blue
   let b = randomVal(255).toString(16);
   if (b.length < 2) b= "0" + b;

   return "#" + r + g + b;
}

function ranNumber() {
   let hex = randomColor();
   document.getElementById("num").style.backgroundColor=hex;
}
</script>

</head>
<body>
<div id="num"></div>
</body>
</html>



PreviousNext

Related