By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
Notification Show More
Latest News
Passing a JavaScript Value Between HTML Pages
Passing a JavaScript Value Between HTML Pages
JavaScript
Compare Objects in an Array
JavaScript Problem: Compare Objects in an Array
JavaScript
Switching Name Order Using Capturing Groups in Regular Expressions
Switching Name Order Using Capturing Groups in Regular Expressions
JavaScript
Shuffling an Array
JavaScript Problem: How to Perform Shuffling an Array
JavaScript
Create a Non-duplicated Collection
JavaScript Problem: Using Set to Create a Non-duplicated Collection
JavaScript
Aa
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > How to Make Random Hex Color Generator In JavaScript
JavaScript

How to Make Random Hex Color Generator In JavaScript

Admin
Last updated: 2022/11/24 at 5:09 AM
Admin
Share
6 Min Read
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.

Contents
what is hex color ๐Ÿค” ?๐Ÿ‘‰ Create a ๐Ÿ“‚index.html ๐Ÿ‘‰ Now Create a ๐Ÿ“‚style.css๐Ÿ‘‰ Create  ๐Ÿ“‚index.js FileUpdating BackgroundCopy Hex Color Code

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

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

TAGGED: Random Hex Color Generator In JavaScript
Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Posted by Admin
Follow:
Rocoderes is a blog you can learn HTML, CSS, JavaScript, React Js and Python along with creative coding stuff and free source code files.
Previous Article meme generator in javascript How to Make Meme Generator in JavaScript
Next Article Number Guessing Game JavaScript How To Make Number Guessing Game JavaScript
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

Passing a JavaScript Value Between HTML Pages

Passing a JavaScript Value Between HTML Pages

February 3, 2023
Compare Objects in an Array

JavaScript Problem: Compare Objects in an Array

January 30, 2023
Switching Name Order Using Capturing Groups in Regular Expressions

Switching Name Order Using Capturing Groups in Regular Expressions

January 29, 2023
Shuffling an Array

JavaScript Problem: How to Perform Shuffling an Array

January 27, 2023
rocoderesrocoderes
Follow US

Copyright ยฉ 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?