Skip to main content

Command Palette

Search for a command to run...

Learn How to Generate Random Colors with JavaScript Like an Expert

Generate random colors with JavaScript

Published
2 min read
Learn How to Generate Random Colors with JavaScript Like an Expert
A

Full-stack developer with a knack for turning complex problems into simple solutions. Always learning, always coding

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.

  • 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>

Code Explanation

  • the HTML code below will create a button element on the HTML document.
<button id="button">Click me</button>
  • 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;
      }
    
  • 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}`;
        })

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.