DEV Community

Cover image for Learn How to Generate Random Colors with JavaScript Like an Expert
Alfred Nwanokwai
Alfred Nwanokwai

Posted on

Learn How to Generate Random Colors with JavaScript Like an Expert

Generating random colors with JavaScript can be a bit intimidating, especially to new developers. in this post, I will walk you through how you can generate random colors with JavaScript.

JavaScript

  • create an index.html file

create an index.html file, and copy and paste the code snippet below into the index.html file.

  <!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>Generate random color</title>

    <style ="text/css">
        body {
            display: grid;
            place-items: center;
            height: 100vh;
        }
        #button {
            height: 50px;
            width: 100px;
        }
    </style>
</head>
<body>

    <button id=" button">Click me</button>

    <script>
        const button = document.getElementById("button");

        button.addEventListener("click", () => {
            const generateRandomColor = `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
            document.body.style = `background-color: ${generateRandomColor}`;
        })
    </script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

See code on codepen

Code ExplanationCode Explanation

  • the HTML code below will create a button element on the HTML document.
<button id="button">Click me</button>
Enter fullscreen mode Exit fullscreen mode
  • I added a little styling to it to place the button element in the center of the HTML document
  body {
    display: grid;
    place-items: center;
    height: 100vh;
  }
   #button {
    height: 50px;
    width: 100px;
  }
Enter fullscreen mode Exit fullscreen mode

Here is the

  • JavaScript code that does the magic.

  • firstly, I search through the Dom tree to retrieve a button element with an id of "button", then I stored it in a variable called button.

  • then, I added an event listener to the button, and I listen to a click event.

  • then the code generates a random color each time the button is clicked.

  • then I assigned the color to the background.

  const button = document.getElementById("button");

        button.addEventListener("click", () => {
            const generateRandomColor = `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
            document.body.style = `background-color: ${generateRandomColor}`;
        })
Enter fullscreen mode Exit fullscreen mode

thank you for reading. please leave a comment below and share the post with your friends who are also learning JavaScript. don't forget to follow me for more useful content.

Top comments (8)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

There are at least 3 problems with your code generating the random colour:

  • The code will never generate #ffffff as Math.floor(Math.random() * x) will only ever get you as high as x-1
  • There are a whole lot more colours that your code will never produce, as you are not padding the result with 0s. For example - #ddd will be interpreted as the colour #dddddd rather than #000ddd - which is an entirely different colour
  • Similar to the second issue, 4 character long colours like abc8 will be interpreted as shorthand #rgba (The long version being #rrggbbaa) - so some colours you are returning will also have random alpha values
Collapse
 
zuxcode profile image
Alfred Nwanokwai

Dear Randy!

Thank you for taking the time to read my articleπŸ™Œ and sharing your valuable insights through your corrective comment. I appreciate your attention to detail and the effort you've put into providing feedbackπŸ˜ƒ. However, I intentionally focused on a more traditional approach in this article to showcase core concepts. πŸ˜ŠπŸ“š
It's always good to stay open to new ideas, though πŸŒŸπŸš€

Collapse
 
karlenkhachaturyan profile image
Karlen Khachaturyan • Edited

Maybe this approach would be better?

function randomColor() {
    const r = Math.floor(Math.random() * 255);
    const g = Math.floor(Math.random() * 255);
    const b = Math.floor(Math.random() * 255);

    return `rgb(${r},${g},${b})`
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
zuxcode profile image
Alfred Nwanokwai

πŸ‘‹Hey Karlen!

Thank you for reading my article and for sharing your suggestion on an alternative way to write the code. I appreciate your input and the opportunity to consider different approaches to solving the problem. I will definitely take this into consideration for future posts. In the meantime, If you have any further suggestions, ideas, or questions, please don't hesitate to reach out. Your input is highly valued, and I am eager to foster meaningful discussions around code development.

Collapse
 
bkpecho profile image
Bryan King Pecho

Thanks! This is a well-written and easy-to-follow tutorial πŸ‘

Collapse
 
zuxcode profile image
Alfred Nwanokwai

Dear Bryan,

Thank you for taking the time to read my article and leaving a comment expressing your gratitude. I appreciate your kind words and I'm glad that you found the article helpful.

It's always rewarding to receive positive feedback and know that the content I create has made a positive impact. As a developer and writer, my goal is to share knowledge and provide valuable resources to the community, so knowing that it has been beneficial to you is truly fulfilling.

If you have any further questions, feedback, or topics you'd like me to cover in future articles, please feel free to let me know. I'm here to assist and provide information that meets the needs and interests of readers like you.

Collapse
 
timlmit profile image
TIM

Thank you

Collapse
 
zuxcode profile image
Alfred Nwanokwai

πŸ‘‹ Hey TIM!

Thank you so much for the kind words! I'm glad you enjoyed the article and I hope it was helpful in some way. If you have any questions or feedback, feel free to let me know!.