How to Build a Random Color Generator

How to Build a Random Color Generator

To begin first create a file called index.html and insert the code below.

<!DOCTYPE html>
<html>
<head>
    <title>Cute Random Color Generator</title>
    <style>
        body {
            background-color: #f1f1f1;
            text-align: center;
            font-family: Arial, sans-serif;
        }

        h1 {
            margin-top: 50px;
        }

        .circle {
            width: 200px;
            height: 200px;
            margin: 50px auto;
            border-radius: 50%;
            border: 2px solid #000;
        }

        #color-text {
            font-size: 24px;
            margin-top: 20px;
        }

        #generate-btn {
            margin-top: 20px;
            padding: 10px 20px;
            font-size: 18px;
            background-color: maroon;
            color: #fff;
            border: none;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>Cute Random Color Generator</h1>
    <div class="circle" id="color-circle"></div>
    <p id="color-text"></p>
    <button id="generate-btn" onclick="generateColor()">Generate Color</button>

    <script>
        function generateColor() {
            var color = getRandomColor();
            document.getElementById("color-circle").style.backgroundColor = color;
            document.getElementById("color-text").innerText = "RGB: " + color;
        }

        function getRandomColor() {
            var r = Math.floor(Math.random() * 256);
            var g = Math.floor(Math.random() * 256);
            var b = Math.floor(Math.random() * 256);
            return "rgb(" + r + ", " + g + ", " + b + ")";
        }
    </script>
</body>
</html>

In the code above we create two functions one to generate the random RGB value and the other function renders the generated value into a color.

Now open your file in the browser and the application should appear as shown below.

There you have it. Thanks for reading.

Leave a Comment

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