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.

  
 lang="en">

     charset="UTF-8">
     http-equiv="X-UA-Compatible" content="IE=edge">
     name="viewport" content="width=device-width, initial-scale=1.0">
    </span>Generate random color<span class="nt">

    



     id=" button">Click me

    



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.
 id="button">Click me
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.

mongo-strict, smart MongoDB ORM for Node JS

Mongo Strict is a TypeScript-based smart MongoDB ORM that makes the usage of MongoDB safer, easier, and faster,…

You May Also Like