Welcome to Coding Torque. In this blog, we are going to create a Random Hex Color Generator using HTML, CSS and JavaScript. You should create this project if you are a beginner and learning JavaScript.
Before we start, here are some more JavaScript Games you might like to create:
1.Ā Snake Game using JavaScript
2.Ā 2D Bouncing Ball Game using JavaScript
3.Ā Rock Paper Scissor Game using JavaScript
4.Ā Tic Tac Toe Game using JavaScript
5.Ā QR Code Generator using JavaScript
I would recommend you don’t just copy and paste the code, just look at the code and type by understanding it.
HTML CodeĀ
Starter Template
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSS --> <link rel="stylesheet" href="style.css"> <title>Random Hex Color Generator using JavaScript with Source Code - @code.scientist x @codingtorque</title> </head> <body> <!-- Further Code here --> <script src="script.js"></script> </body> </html>
Paste the below code in your <body>
tag
<div class="container"> <p id="hex">#ffffff</p> <Button id="generateBtn" onclick="generateHex()">Generate Hex Color</Button> </div>
Output Till Now
CSS CodeĀ
Create a fileĀ style.css
and paste the code below.
@import url("https://fonts.googleapis.com/css2?family=Poppins"); * { margin: 0; padding: 0; box-sizing: border-box; font-family: "Poppins", sans-serif; } .container { display: flex; align-items: center; justify-content: center; flex-direction: column; margin: 10rem 0; } #hex { font-size: 1.2rem; font-weight: bold; background-color: white; padding: 5px 10px; margin-bottom: 5px; border-radius: 5px; } #generateBtn { padding: 8px 12px; background: black; color: white; border: none; cursor: pointer; font-size: 1.5rem; border-radius: 10px; }
Output Till Now
JavaScript CodeĀ
Create a fileĀ
script.js
Ā and paste the code below.function generateHex() { let charset = "0123456789ABCDEF", hex = ""; for (var i = 0, n = charset.length; i < 6; ++i) { hex += charset.charAt(Math.floor(Math.random() * n)); } document.getElementById("hex").innerText = `#${hex}`; document.querySelector("body").style.background = `#${hex}`; }
Written by: Piyush Patil
If you have any doubts or any project ideas feel free to Contact Us
Hope you find this post helpfulš