Logo

dev-resources.site

for different kinds of informations.

Let’s Create a Random-Color Generator!

Published at
1/13/2025
Categories
javascript
tutorial
webdev
beginners
Author
Ethan Groene
Let’s Create a Random-Color Generator!

If you’re new to JavaScript, you have probably learned a lot about how the data types, logic, functions, etc. work. This is good; to use JS in more-complicated projects someday, you need to start with the fundamentals. However, depending on your attention span, you may soon start feeling the strong desire to put your JS skills to work on an actual website. Doing so can be a bit complicated (but not as complicated as Regular Expressions, amirite), but one of the simpler ones you can start with is, you guessed it, a random-color generator. In this article, I’ll take you through the steps I used to build one myself.

1. Add boilerplate HTML

<!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-Color Generator</title>

  <!--Link stylesheets-->
  <link rel="stylesheet" href="./styling.css">
  <link rel="stylesheet" href="./responsive.css">
</head>

If you’re using VS Code, you can type '!' into the empty HTML document, then press 'Enter' to add this part (not sure about other text editors) if you didn’t know that already. Below the boilerplate, I added links to the CSS documents I used for this project. I recommend keeping your CSS in a separate file, just so that your HTML file doesn’t get too big & complicated. Since the JavaScript we’ll be writing is not super long, I’ll be adding that directly to the HTML file inside the <script> tag, which you’ll see in step 3. If you wanted to have a separate JS file and link it to your HTML file, you could do this:

<script type="text/javascript" src="main.js"></script>

2. Build the HTML ‘skeleton’

<body onload="getNewColor()">
  <div id="heading">
    <h1>Need a random color? Then you've come to the right place!</h1>
    <h2>Please select a color by clicking the button below.</h2>
  </div>
  <div class="color">
    <span id="hex"></span>
    <button onclick="getNewColor()">Get New Color!</button>
  </div>

Now that we’ve added the boilerplate HTML & linked our CSS documents in the <head>, let’s add the body & build out our HTML. As you can see, the getNewColor() function will run whenever the page loads. More on this function in the following steps.

In the picture above, I add a <div>, which contains a couple of headers, letting the user know where they are & what to do. I then add another <div>, which contains a <span> tag, which will eventually be populated with a HEX code and will display as text on the page. Next, I insert a button that the user clicks to generate a new HEX code. This is done by the getNewColor() function, which I will explain soon.

3. Add JavaScript!

Now we are at the point where the real magic starts to happen. Are you excited? I can tell. Here’s how you do that:

<script>
  function getNewColor() {
    let symbols = "0123456789ABCDEF";
    let color = "#";

For a relatively simple program like this, we can accomplish what we need to with only one function, the aforementioned getNewColor() function. For this generator, let’s use HEX codes to determine the color, but using RGB values is also possible.

Let’s first put all the possible HEX characters (integers 0–9 & letters A-F) in the form of a string, into a variable called symbols.

Then, let’s initialize the color variable with a hash mark in the form of a string. This variable will be mutated in the loop described below.

Let’s now make a loop that runs 6 times, since there are 6 values in a HEX code. For every loop iteration, a single random value from the symbols string is added to the variable color, which, if you remember, starts with # in string form. At this point, whenever we call the getNewColor(), we get a new HEX code. Now, let’s apply that code to our HTML page.

In my experience, it’s worked best to put the <script> tag at the end of the <body> tag. Some would vehemently argue otherwise, and they may have a point, but I’m not going to discuss that in this article. Please have a keyboard war in the comment section below if you feel inclined, as it’s good for engagement.

4. Apply JS to HTML file

Cool, we now have a function that gives us a random HEX code. However, this is useless unless we apply it to our HTML. In this case, it’d be nice to change the background of the entire page, so the user can have a preview of the random color, and to put the HEX code in text format, so they can copy it. We’ll first need to define these behaviors in our function:

// continuing getRandomColor()...
    document.body.style.background = color;
    document.getElementByID("hex").textContent = color;
  </script>
</body>
</html>

Still operating inside the getNewColor() function, we can access the background styling property with the first line of code you see in the above photo. We could have also used backgroundColor, which, by the way, translates to background-color in CSS. In this step, we set the variable color, which we randomly defined in the loop, as the background color for the page.

In the second line of code, we access the previously defined <span> tag by its id, ‘hex’. To add the variable color in text form, we can use the method .textContent, which I’ve used here, or the .innerHTML method, to append color to the <span> tag. See the link at the end of this article to read more on the difference between these. In the way we laid out our HTML above, this text will appear directly above the button so the user can see the exact color displayed & copy it if they want.

Altogether, our JS looks like this:

<script>
        function getNewColor() {
            let symbols = '0123456789ABCDEF';
            let color = '#'
            for (let i = 0; i < 6; i++) { // Hex code can only go up to 6, so i < 6. This loop runs once for every function call.
                color += symbols[Math.floor(Math.random() * 16)]; // 16 because of all the different possibilities in a hex code
            }
            document.body.style.background = color; // changes the background of the body to the value of var color
            document.getElementById("hex").textContent = color; /* text value of var color (current color's hex code) is displayed above the button & inside the span tag */
        }
    </script>

5. Tell the program when to run the function

There’s no point in making a function if we never run it, so let’s now tell our program when our getNewColor() function should be called. In this instance, let’s run getNewColor() whenever the page loads & when the ‘Get New Color!’ button is clicked. Here’s how we do that:

// Run getNewColor() upon loading of page:
<body onload="getNewColor()">

// Run getNewColor() when clicking "Get New Color!" button:
<button onclick="getNewColor()">Get New Color!</button>

6. Add styling

You may do this part as you wish or not at all, but here is the styling I used on this project:

/* styling.css */
body {
    margin: 0;
    padding: 0;
    font-family: 'Courier New', Courier, monospace;
}

#heading {
    background-color: rgba(0, 0, 0, 0.4);
    color: white;
    text-align: center;
    padding: 16px;
}

.color {
    text-align: center;
    background-color: rgba(0, 0, 0, 0.4);
    padding: 48px 32px;
    margin: 136px 384px;
}

#hex, #rgb {
    display: block;
    color: white;
    font-size: 40px;
    text-transform: uppercase;
    margin-bottom: 24px
}

#rgb {
    font-size: 32px;
}

.color button {
    background: none;
    outline: none;
    color: white;
    border: 3px solid white;
    cursor: pointer;
    font-size: 24px;
    padding: 8px;
    font-family: 'Courier New', Courier, monospace;
}

/* responsive.css */
@media screen and (max-width: 768px) {
    .color {
        margin: 118px 213px;
    }   

    #hex {
        font-size: 32px;
    }

    .color button {
        font-size: 20px;
        padding: 3px;
    }
}

@media screen and (max-width: 425px) {
    #heading {
        font-size: small;
    }

    .color {
        margin: 89px 66px;
    }


}

@media screen and (max-width: 325px) {
    .color {
        margin: 101px 66px;
    }

    #hex {
        font-size: 25px;
    }

    .color button {
        font-size: 14px;
        padding: 8px;
    }
}

7. Let’s test it out!

If you correctly followed the steps above, a random color will be generated when the page loads, as well as when you click the button. The background of the page will be set to the random color & users can copy the HEX code.

Thanks for reading this far! I hope you found it helpful. Remember, it’s OK to read articles & follow tutorials sometimes, but you should only be doing this to learn concepts. Once you think you’ve got the concepts down pat, try making programs yourself. No, you probably won’t get everything right the first time, but encountering a problem & figuring out how to solve it yourself, using concepts you’ve learned, is the way to becoming a better coder.

If you found this article helpful, I’d appreciate a nice comment or a few claps, so I can know what content people find useful, and so I can focus on writing that content in the future.

As always, happy coding!

See this project in action

Link to this project’s GitHub repo

Link to article on differences between .innerHTML & .textContent

Originally published on Medium for JavaScript in Plain English on August 15, 2022

Featured ones: