27.4 C
Gujarat
HomeJavascriptRandom Hex Color Generator In JavaScript

Random Hex Color Generator In JavaScript

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

Random Hex Color Generator In JavaScript
<!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

Adminhttps://rocoderes.com
Rocoderes is a blog you can learn HTML, CSS, JavaScript, React Js and Python along with creative coding stuff and free source code files.
RELATED ARTICLES

3 COMMENTS

  1. I’ve been browsing online more than three hours today, yet I never found any interesting article like yours. Itโ€™s pretty worth enough for me. In my opinion, if all website owners and bloggers made good content as you did, the internet will be a lot more useful than ever before.

  2. Hello there, just became alert to your blog through Google, and found that it’s really informative. Iโ€™m gonna watch out for brussels. Iโ€™ll appreciate if you continue this in future. A lot of people will be benefited from your writing. Cheers!

  3. You actually make it seem so easy with your presentation but I find this topic to be actually one thing that I feel I’d never understand. It sort of feels too complicated and very wide for me. I’m looking ahead on your subsequent publish, I will try to get the hang of it!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

15,000FansLike
5,000FollowersFollow
535FollowersFollow
- Advertisment -spot_img

Subscribe to our newsletter

To be updated with all the latest news, offers and special announcements.

Most Popular