🍭 Creating a Random Color Generator with Copy-to-Clipboard 📋 in HTML, CSS, and JavaScript
July 01, 20255 min read

🍭 Creating a Random Color Generator with Copy-to-Clipboard 📋 in HTML, CSS, and JavaScript

Web developmentJavaScriptCSS3JavaScript Projects
share this article on

A random color generator is a fun and useful tool that allows users to generate and copy random colors in different formats, such as HEX, RGB, and HSL. In this tutorial, we will build an interactive color generator with a format selection dropdown and a copy-to-clipboard feature using HTML, CSS, and JavaScript.

✨ Features of the Random Color Generator

🧱 Project Structure

/random-color-generator
  ├── index.html
  ├── styles.css
  └── script.js

🖼️ HTML Code for Random Color Generator

The HTML file contains the main structure of the page, including the color display, dropdown, and buttons.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Color Generator</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <h1>Random Color Generator</h1>
        <!-- Dropdown for Color Format -->
        <select id="color-format">
            <option value="hex">HEX</option>
            <option value="rgb">RGB</option>
            <option value="hsl">HSL</option>
        </select>
        <div class="color-box">
            <span id="color-code">#FFFFFF</span>
            <button id="copy-btn">📋</button>
        </div>
        <button id="generate-btn">Generate Color</button>
    </div>
</body>
<script src="script.js"></script>
</html>

🎨 CSS Code: Styling for Random Color Generator

The CSS file is responsible for styling the interface, making it visually appealing.

body {
    font-family: Arial, sans-serif;
    text-align: center;
    background-color: #161a20;
    color: #fff;
    margin: 0;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

.container {
    background: #222;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

h1 {
    margin-bottom: 15px;
}

/* Dropdown Styling */
#color-format {
    margin-bottom: 15px;
    padding: 8px;
    font-size: 16px;
    border-radius: 5px;
    border: none;
    cursor: pointer;
}

.color-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #333;
    padding: 15px;
    border-radius: 5px;
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 15px;
}

#color-code {
    margin-right: 10px;
}

button {
    padding: 10px 15px;
    border: none;
    cursor: pointer;
    font-size: 16px;
    border-radius: 5px;
    transition: 0.3s;
}

#copy-btn {
    background: #555;
    color: white;
}

#copy-btn:hover {
    background: #777;
}

#generate-btn {
    background: #008CBA;
    color: white;
}

#generate-btn:hover {
    background: #0074A6;
}

🧠 JavaScript Functionality

The JavaScript file contains the logic for generating colors, changing formats, and copying the color value to the clipboard.

document.addEventListener("DOMContentLoaded", () => {
    const colorCode = document.getElementById("color-code");
    const generateBtn = document.getElementById("generate-btn");
    const copyBtn = document.getElementById("copy-btn");
    const colorFormat = document.getElementById("color-format");

    let currentColor = { r: 0, g: 0, b: 0 }; // Store the current color in RGB format

    function getRandomColor() {
        const r = Math.floor(Math.random() * 256);
        const g = Math.floor(Math.random() * 256);
        const b = Math.floor(Math.random() * 256);
        return { r, g, b };
    }

    function rgbToHex(r, g, b) {
        return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;
    }

    function rgbToHsl(r, g, b) {
        r /= 255;
        g /= 255;
        b /= 255;

        const max = Math.max(r, g, b);
        const min = Math.min(r, g, b);
        let h, s, l = (max + min) / 2;

        if (max === min) {
            h = s = 0; // achromatic
        } else {
            const d = max - min;
            s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
            switch (max) {
                case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                case g: h = (b - r) / d + 2; break;
                case b: h = (r - g) / d + 4; break;
            }
            h /= 6;
        }

        h = Math.round(h * 360);
        s = Math.round(s * 100);
        l = Math.round(l * 100);

        return `hsl(${h}, ${s}%, ${l}%)`;
    }

    function updateColorDisplay() {
        // Update the displayed color based on the current format
        let formattedColor;
        switch (colorFormat.value) {
            case "rgb":
                formattedColor = `rgb(${currentColor.r}, ${currentColor.g}, ${currentColor.b})`;
                break;
            case "hsl":
                formattedColor = rgbToHsl(currentColor.r, currentColor.g, currentColor.b);
                break;
            default:
                formattedColor = rgbToHex(currentColor.r, currentColor.g, currentColor.b);
        }

        colorCode.textContent = formattedColor;
    }

    function generateNewColor() {
        // Generate a new random color and update the display
        currentColor = getRandomColor();
        document.body.style.backgroundColor = `rgb(${currentColor.r}, ${currentColor.g}, ${currentColor.b})`;
        updateColorDisplay();
    }

    copyBtn.addEventListener("click", () => {
        console.log("Copy button clicked"); // Debugging log
        navigator.clipboard.writeText(colorCode.textContent).then(() => {
            copyBtn.textContent = "✅ Copied!";
            setTimeout(() => copyBtn.textContent = "📋 Copy", 1500);
        });
    });

    generateBtn.addEventListener("click", () => {
        console.log("Generate button clicked"); // Debugging log
        generateNewColor();
    });

    colorFormat.addEventListener("change", () => {
        console.log("Dropdown changed to:", colorFormat.value); // Debugging log
        updateColorDisplay();
    });

    // Generate a random color on page load
    generateNewColor();
});

Conclusion

With this Random Color Generator, users can generate colors in HEX, RGB, or HSL format, copy the values easily, and see real-time background changes. Try modifying the styles or adding a history feature to track previous colors! 🚀

Happy coding!


Back to Articles