
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
<!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.
Advertisements