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)

HTML

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>
<button>Generate</button>

CSS

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

@import url('https://fonts.googleapis.com/css2?family=Open+Sans&display=swap');
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body{
    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 {
    outline:none;
}
p { 
    font-size: 32px;
}

JavaScript

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;
    text.innerHTML = color;
    document.body.style.background = color;
})

Here is the Github repository link: https://github.com/code-architects/generate-random-hex-color

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

Happy Coding 💞

Leave a Comment

Comments

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

Leave a Reply

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

four + 17 =