Generate Random Color with JavaScript

Generate color with Javascript | Code Architects

Whether you’re a beginner or an experienced developer, this guide will help you generate random color with JavaScript to your web projects in new and exciting ways.

Preview (Generate Random Color with JavaScript)


For this project of generate color with JavaScript we only need 2 HTML elements. A <p> tag with id of color & a <button> that can be used to generate a onClick event.

<p id='color'></p>


Align the HTML Center to the center of the page by using display:flex & align-items: center

@import url('');
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Open Sans', sans-serif;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    transition: 0.2s;
button {
    margin-top: 20px;
    border: 0;
    background: #eee;
    color: #000;
    padding: 12px 20px;
    box-shadow: 0px 4px 8px rgba(0,0,0,0.3);
button:focus, button:active {
p { 
    font-size: 32px;


let text = document.querySelector("#color");
document.querySelector("button").addEventListener("click", () => {
    let colorletter = "";
    let letters = '0123456789ABCDEF';
    for (var i = 0; i < 6; i++) {
        colorletter += letters[Math.floor(Math.random() * 16)];
    let color = "#" + colorletter;

    // Use the color wherever you want to use.
    text.innerHTML = color; = color;

Each time the JavaScript button is clicked it fires a click event. It has a function executed when the click event triggers. A for..loop uses Math.random() which fetches letters from the letters & After running the loop 6 times. add the # to that 6 letter random word, to format it like a HEX Color. You can now use this color in your website anywhere you can.

Here is the Github repository link:

This project was a part of our 15 Days – 15 Projects series. Read more projects 👇

Happy Coding 💞

Leave a Comment


No comments yet. Why don’t you start the discussion?

Leave a Reply

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

eighteen − fourteen =