How to Generate Random Colors Using JavaScript
In this Javascript tutorial, we will explore a JavaScript code that generates random colors and applies them dynamically to four child elements within an HTML container.
Project Source Code:
<!DOCTYPE html>
<html>
<head>
<title>Random Color Generator</title>
<style>
body{ margin: 0; padding: 0; background-color: #f9f9f9;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.container{ max-width: 1200px; margin: 0 auto; padding: 2rem; text-align: center; }
.content{ display: flex; flex-wrap: wrap; justify-content: center; margin: 2rem 0;}
.child{ width: 250px; height: 250px; border: 1px solid #ddd; margin: 1rem;
border-radius: 4px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
#generate-btn{ padding: 0.5rem 1rem; border: none; border-radius: 4px;
color: #fff; background-color: orange; font-size: 1rem;
cursor: pointer; transition: all 0.3s ease;
}
#generate-btn:hover{ background-color: darkorange;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2);
}
</style>
</head>
<body>
<div class="container">
<div class="content">
<div class="child" id="child1"></div>
<div class="child" id="child2"></div>
<div class="child" id="child3"></div>
<div class="child" id="child4"></div>
</div>
<button id="generate-btn">Generate Random Colors</button>
</div>
<script>
// Get references to the four child elements in the HTML
const child1 = document.getElementById("child1");
const child2 = document.getElementById("child2");
const child3 = document.getElementById("child3");
const child4 = document.getElementById("child4");
// This function generates a random color in hexadecimal format
function generateRandomColors()
{
let letters = "0123456789ABCDEF"; // String containing all possible hex digits
let color = "#"; // Initialize the color string with the # symbol
// Generate six random hexadecimal digits to form a color
for(let i = 0; i < 6; i++)
{
// Add a random hex digit to the color string
color += letters[Math.floor(Math.random() * 16)];
}
return color; // Return the generated color string
}
// This function changes the background color of the four child elements
// to randomly generated colors
function changeBackgroundColor()
{
child1.style.backgroundColor = generateRandomColors();
child2.style.backgroundColor = generateRandomColors();
child3.style.backgroundColor = generateRandomColors();
child4.style.backgroundColor = generateRandomColors();
}
// Get a reference to the HTML button element with the ID "generate-btn"
const generateBtn = document.getElementById("generate-btn");
// Add a "click" event listener to the button,
// which triggers the changeBackColor function
generateBtn.addEventListener("click", changeBackgroundColor);
</script>
</body>
</html>
Code Explanation:
This JavaScript code performs the following actions:
1 - HTML Structure: The HTML code consists of a container div that encapsulates four child div elements. Each child div has a unique ID assigned to it.
2 - Retrieving HTML Element References: Using the document.getElementById() method, the code retrieves references to the four child elements and assigns them to respective variables (child1, child2, child3, and child4).
3 - Generating Random Colors: The generateRandomColors() function generates a random color in hexadecimal format. It does so by concatenating six random hexadecimal digits (0-9, A-F) to form a valid color code.
4 - Changing Background Colors: The changeBackgroundColor() function changes the background color of each child element by setting the style.backgroundColor property to a randomly generated color obtained from the generateRandomColors() function.
5 - Event Handling: The code attaches an event listener to the button element with the ID "generate-btn" using the document.getElementById() method. When the button is clicked, the changeBackgroundColor() function is triggered, resulting in a new set of random colors being applied to the child elements.
OUTPUT: