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 −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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>
<div id="chooseColor" style="width:100px;height:100px;background-color:#FF0"></div>
<button onclick="pickRandomColor()">Click the button to get random color</button>
   //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());

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 −


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

Above, we successfully generated random color.