Hi everyone! After a long break, I here with a awesome method from JavaScript. When you visit websites, you often see different colors that make them look attractive. Did you know you can make your webpage change colors randomly with just a few lines of JavaScript?
Today, I learned how to generate random colors using hex codes in JavaScript. Let me explain step by step.
What is a Hex Color?
Colors on the web can be written in different ways, and one of the most popular formats is hexadecimal (hex) colors.
- A hex color starts with #.
- It is followed by 6 characters.
- These characters can be numbers (0–9) or letters (A–F).
👉 Example:
- #FF0000 = Red
- #00FF00 = Green
- #0000FF = Blue
Since each position has 16 possibilities (0–9 and A–F), there are more than 16 million possible colors!
The Logic Behind Random Colors:
To generate a random hex color, we need to:
- Create an array with all possible hex characters (0–9 and A–F).
- Pick random characters from that array.
- Repeat the process 6 times (because hex codes have 6 digits).
- Add # at the beginning.
- Apply it to the background of our webpage.
The JavaScript Code:
Here’s the complete code:
<!DOCTYPE html>
<html>
<head>
<title>Random Color Generator</title>
</head>
<body class="body">
<button onclick="randomValue()">Click me</button>
<script>
// Step 1: Hex characters array
let color = [0,1,2,3,4,5,6,7,8,9,"A","B","C","D","E","F"];
// Step 2: Function to get one random character
function getRandomDigit() {
let index = Math.floor(Math.random() * color.length);
return color[index];
}
// Step 3: Function to generate full hex code
function randomValue() {
let hexa = "#"; // start with #
for (let i = 0; i < 6; i++) {
hexa += getRandomDigit(); // add 6 random characters
}
document.querySelector(".body").style.backgroundColor = hexa;
}
</script>
</body>
</html>
How It Works:
- Click the button.
- JavaScript generates a random 6-character hex code.
- That color is applied to the background of the webpage.
👉 Example: If the generated code is #3FA2C1, your page will turn into that color!
Conclusion:
This small project is a fun way to practice:
- Arrays (storing characters),
- Loops (repeating steps),
- DOM Manipulation (changing webpage background).
Now you can impress your friends by showing them a website that changes colors every time you click a button!
That's it guys. I hope it will be helpful for someone who wants to make them website more style and vibrant.Thank you for reading my blog. Will see you in my next blog.
Reference:
Top comments (0)