DEV Community

SEENUVASAN P
SEENUVASAN P

Posted on

Day:5 JavaScript Project: Changing Colors with a Button

Today was an exciting day in my coding journey — I learned about JavaScript, specifically arrays, array length, Math.random(), and Math.floor(). To put my new knowledge into action, I built a small project where the background color changes every time you click a button. It was a fun and interactive way to understand these concepts better!

What I Learned

Arrays in JavaScript: These are used to store multiple values in a single variable.

.length property: This tells you how many items are in the array.

Math.random(): Generates a random number between 0 and 1.

Math.floor(): Rounds a number down to the nearest whole number  useful for selecting a random array index.
Enter fullscreen mode Exit fullscreen mode

The Project: Color Changer

simple HTML and JavaScript code I wrote:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Color Change</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
    </style>
</head>
<body>
    <button class="btn btn-dark" onclick="change()">Change Color</button>

    <script>
        function change() {
            let colors = ["red", "blue", "yellow", "green"];
            let len = colors.length;
            let random = Math.random() * len;
            let floor = Math.floor(random);
            document.body.style.backgroundColor = colors[floor];
        }
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

How It Works

When the button is clicked, the change() function runs.

An array of colors is defined: ["red", "blue", "yellow", "green"].

A random number is generated between 0 and the array length using Math.random() * len.

Math.floor() converts it to a whole number to use as an index.

The background color of the page changes based on that random index!

Enter fullscreen mode Exit fullscreen mode




Output

Image description

Final Thoughts

This was a small project, but it taught me a lot about how JavaScript interacts with HTML and CSS. I’m excited to keep learning and build more interactive web pages!

Top comments (0)