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
JavaScript to generate random hex codes of color
To generate random hex codes of color using JavaScript, the code is as follows −
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>
<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 −

Advertisements