

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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.
- Related Questions & Answers
- Random name generator function in JavaScript
- Random number generator in Java
- Generating random hex color in JavaScript
- JavaScript Generator
- JavaScript to generate random hex codes of color
- Explain Generator functions in JavaScript?
- What are generator functions in JavaScript?
- JavaScript Random
- Induction Generator (Asynchronous Generator)
- What are async generator methods in JavaScript?
- C++ Program to Implement the linear congruential generator for Pseudo Random Number Generation
- How to create a password generator - JavaScript?
- Hexadecimal color to RGB color JavaScript
- RGB color to hexadecimal color JavaScript
- Generate random string/characters in JavaScript?
Advertisements