Random color generator in JavaScript


Following is the syntax to generate random color in JavaScript −

$("#yourIdName").css("background-color", yourCustomFunctionNameToGetRandomColor());

Following is the JavaScript code −

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>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div id="chooseColor" style="width:100px;height:100px;background-color:#FF0"></div>
<button onclick="pickRandomColor()">Click the button to get random color</button>
</body>
<script>
   //The getColorCode() will give the code every time.
   function getColorCode() {
      var makeColorCode = '0123456789ABCDEF';
      var code = '#';
      for (var count = 0; count < 6; count++) {
         code =code+ makeColorCode[Math.floor(Math.random() * 16)];
      }
      return code;
   }
   //Function call on button click.
   function pickRandomColor() {
      $("#chooseColor").css("background-color", getColorCode());
   }
</script>
</html>

To run the above program, save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS code editor.

By default, it will give yellow color, and when you will click the button, random color will be displayed. Following is the output −

Output

Following is the snapshot of sample output after clicking the button Click the button to get random color

Above, we successfully generated random color.

Updated on: 16-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements