JavaScript to generate random hex codes of color

JavascriptWeb DevelopmentObject Oriented Programming

To generate random hex codes of color using JavaScript, the code is as follows −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      box-sizing: border-box;
      font-size: 18px;
      font-weight: 500;
      color: white;
      width: 150px;
      height: 150px;
      text-align: center;
      padding-top: 4%;
   }
</style>
</head>
<body>
<h1>Generate random hex codes of color</h1>
<button class="Btn">GENERATE</button>
<div class="result"></div>
<h3>
Click on the above button to generate a random hex color code
</h3>
<script>
   let resultEle = document.querySelector(".result");
   let hexCode = "0123456789ABCDEF";
   let Color = "#";
   document.querySelector(".Btn").addEventListener("click", () => {
      for (let i = 0; i < 6; i++)
         Color += hexCode[Math.floor(Math.random() * 16)];
      resultEle.style.backgroundColor = Color;
      resultEle.innerHTML = Color;
   });
</script>
</body>
</html>

Output

On clicking the ‘GENERATE’ button −

raja
Published on 12-May-2020 06:18:35
Advertisements