In this post, We will learn how to make Random Hex Color Generator In JavaScript. It is a simple page that generates a random hexadecimal color code. When you click a button and update the background of the page to correspond with the generated color code and also you can copy the color code click on the copy button.
what is hex color 🤔 ?
A HEX color is expressed as a six-digit combination of numbers and letters defined by its mix of red, green, and blue (RGB). Hex color codes start with a pound sign or hashtag (#) and are followed by six letters and/or numbers.
You can see the Demo Here Random Hex Color Generator In JavaScript
👉 Create a 📂index.html
Here we are making attractive UI
<!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 Hex Color Generator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wrapper">
<div id="screen"></div>
<div id="output">
<div id="code">#cccccc</div>
<button id="copyBtn"></button>
</div>
<button id="generateBtn">Generate</button>
</div>
<script src="index.js"></script>
</body>
</html>
👉 Now Create a 📂style.css
I give the page a default background color of #cccccc, added a transition effect to make the color change smoother, and set its height and width to that of the viewport which is the user’s visible area of a web page. Then I went ahead to center the contents of the page using CSS Flexbox.
*{
padding:0;
margin:0;
box-sizing: border-box;
}
html,body{
width: 100%;
height: 100%;
}
body{
display: flex;
flex-flow: column;
align-items: center;
justify-content: center;
background-color: aliceblue;
}
.wrapper{
width:300px;
padding: 40px;
overflow: hidden;
border-radius: 10px;
background-color: #212531;
box-shadow: 0 0 10px 8px #0007;
}
#screen,#output,#generateBtn{
width:100%;
}
#screen{
padding: 7px;
aspect-ratio: 1;
border-radius: 50%;
border:5px solid #fff;
}
#screen::before{
content: "";
display: block;
width: 100%;
height: 100%;
border-radius: inherit;
background-color:var(--color,#ccc);
}
#output{
margin: 40px 0;
padding: 10px;
border-radius: 5px;
border: 2px dashed #fff;
font-size: 25px;
color:#fff;
display: flex;
flex-flow:row nowrap;
align-items: center;
justify-content: space-between;
}
#copyBtn{
width: 30px;
height: 30px;
border: none;
cursor: pointer;
border-radius: 50%;
background-color: #888a90;
background-image: url('./copy.png');
background-repeat: no-repeat;
background-position:center;
background-size: 60%;
transition: transform 0.15s ease;
}
#copyBtn:active{
transform: scale(1.2);
}
#generateBtn{
border:none;
padding: 15px;
cursor: pointer;
font-size: 20px;
border-radius: 5px;
text-transform: uppercase;
transition: transform 0.15s ease;
}
#generateBtn:active{
transform: translateY(-5%);
}
💡 Now It’s time For Javascript Code 😎.
👉 Create 📂index.js File
The first thing I did was to create references to the necessary HTML elements.
const screen=document.querySelector('#screen')
const code=document.querySelector('#code')
const copyBtn=document.querySelector('#copyBtn')
const generateBtn=document.querySelector('#generateBtn')
Then I stored hexadecimal value in the hexString variable and added a click event listener to the generateBtn button.
const hexString="0123456789abcdef";
generateBtn.addEventListener('click',()=>{
let color=generateHexColor(hexString)
})
I defined the generateHexColor function of the event listener as follows
function generateHexColor(hexString) {
let c = "#";
for (let i = 0; i < 6; i++) {
c += hexString.charAt(Math.floor(Math.random() * hexString.length));
}
return c;
}
Every time the button is clicked, the generateHexColor function is called which creates a variable hex and sets its value to #. Then it loops over the hexString and each time generates a random number using Math.random().
Now, the Math.random() function picks a random number between 0 and 1 (not including 1) and returns a decimal but we don’t want decimals. So what do we do if we want a whole number larger than 1? We multiply it by the number we want (in this case, the length of the hexString ) and wrap it within the Math.floor() function which returns the largest integer less than or equal to a given number. It basically rounds it down to the nearest whole number. and charAt() is a method that returns the character from the specified index.
Then add it to the end of the hex variable Then the cycle repeats itself until the 6th round is over at which time a full 6-digit hex code will have been generated.
Updating Background
Now we have a hex color code. so now we set the background color in the body and also set the hex color code textContent in the code section
generateBtn.addEventListener("click", () => {
let color = generateHexColor(hexString);
screen.style.setProperty("--color", color);
document.body.style.background = color;
code.textContent = color;
});
Copy Hex Color Code
add a click event listener to the copyBtn button
copyBtn.addEventListener("click", () => {
navigator.clipboard.writeText(code.textContent);
});
Here we use navigator.clipboard for a copy. There’s another way to make copy/paste work, using the document.execCommand()
Full source code: Random Hex Color Generator In JavaScript
👉 watch the video Random Hex Color Generator Using Vanilla JavaScript | JavaScript Projects | ProgrammingTT
Also Check: 15 JavaScript Basic Concepts You Should Know