Random Hex Color Generator using HTML, CSS and JavaScript - Coding Torque

Random Hex Color Generator using HTML, CSS and JavaScript

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 projects for you to practice:

1. Filter Cards using JavaScript

2. Typing Effect using JavaScript

3. Email Validator using JavaScript

4. Tip Calculator 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.


Let's go step by step:

Step 1: 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

Step 2: 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

Random Hex Color Generator using JavaScript


Step 3: 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: Coding Torque | Piyush Patil

If you want me to code any project or post any specific post, feel free to DM me at IG @code.scientist or @codingtorque

If you have any doubts or any project ideas feel free to Contact Us 

Hope you find this post helpful💖 
 
 Follow us on Instagram for more projects like this👨‍💻 

Post a Comment

Previous Post Next Post