Hello wizards, I hope you are doing great. If you're looking for a fun and easy coding project to work on, look no further than the random color generator! This project is perfect for beginners who are just starting to learn HTML, CSS, and JavaScript, and it's a great way to practice your coding skills.
In this blog, we'll walk you through the steps to create your own random color generator project using HTML, CSS, and JavaScript.
Preview
In the above video, you’ve seen the preview of the "Random Color Generator" project. Now, let's make the project by following steps.
Step 1: Setting up the HTML code
First, let's set up our HTML file. We'll start by creating a button within a body that will generate a new random color when clicked.
Here's what the HTML code looks like :
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Random Color</title> <link rel="stylesheet" href="style.css"> </head> <body> <button class="btn">Button</button> <script src="index.js"></script> </body> </html>
Step 2: Style your HTML elements with CSS
Next, let's add some CSS to style our button and body. We'll give our button a background color and some padding to make it stand out, and we'll center our button on the body.
Here's what the CSS code looks like:
CSS
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@100;200;300;400;500;600;700;800;900&display=swap"); * { margin: 0; padding: 0; box-sizing: border-box; font-family: "Poppins", sans-serif; } body { display: flex; justify-content: center; align-items: center; height: 100vh; } .btn { text-transform: uppercase; padding: 10px 20px; font-size: 24px; background-color: white; color: black; cursor: pointer; box-shadow: 4px 4px 0 black; } .btn:active { position: relative; top: 4px; left: 4px; box-shadow: none; }
Step 3: Adding functinality using JavaScript
Now, let's move on to the fun part: generating random colors with JavaScript. We'll use the array of random colors, which uses green, blue, orange, red, yellow and violet colors. after that we will access each color randomly when user clicks the button.
Here's what the JavaScript code looks like:
JavaScript
const bodyEl = document.querySelector("body"); const btnEl = document.querySelector(".btn"); var colors = ["green","blue","orange","red","yellow","violet"]; bodyEl.style.background = "pink"; btnEl.addEventListener("click",addColor); let count = 0; function addColor(){ var color = parseInt(Math.random()*colors.length); bodyEl.style.background = colors[color]; }
Generating Download Link...