Random Color Generator Using JavaScript with Source Code

Add a splash of creativity to your projects with our Random Color Generator project using JavaScript. In this article, we’ll guide you through the development process and provide the source code to create a dynamic tool that generates an array of vibrant and unique colors, offering endless possibilities for design and artistic expression.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Color Generator</title>
    <link rel="stylesheet" href="./style.css" type="text/css">
    <div class="container">
        <p class="hex-value">Where's my Color</p>
        <p class="how-to">Tap above or press SPACE</p>
    <script src="./script.js" type="text/javascript"></script>

    margin: 0;
    padding: 0;
    box-sizing: border-box;
body {
    font-size: 10px; /* 1rem = 10px */
    font-family: 'lato', Arial, sans-serif;
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
.container {
    background: #000;
    border-radius: 1rem;
    padding: 1.2rem 2.5rem;
    color: white;
    min-width: 26rem;
    text-align: center;
    font-size: 4rem;
.how-to {
    text-align: center;
    font-size: 1.5rem;
    margin-top: 2rem;

const hexValueElement = document.querySelector('.hex-value');

function generateHEX(){
    let randomHex = 
        Math.random() //random number between 0 and 1
        .toString(16) //convert that number to hexadecimal string (i.e, base 16)
        .substr(-6);  //grab last 6 digit string
    let randomHexColor = `#${randomHex}`;    
    hexValueElement.textContent = randomHexColor;
    document.body.style.background = randomHexColor;     

function keybord(event){
    if(event.code == 'Space'){

//when user clicks on HEX value
hexValueElement.addEventListener('click', generateHEX);

//when user clicks on spacebar
window.addEventListener('keydown', keybord);

Leave a Reply