DEV Community

Cover image for 👨‍💻 Daily Code 51 | Color Flipper Button in 🟨 JavaScript
Gregor Schafroth
Gregor Schafroth

Posted on

👨‍💻 Daily Code 51 | Color Flipper Button in 🟨 JavaScript

Today I gave myself the exercise to create a button button that background color of a website to a random one

My Code

I forgot to document step by step today, but here is the code that achieves my goal

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exercise: Create a 'Color Flipper' Button</title>
</head>

<body>
    <button id="js-button">Color Flipper</button>

    <script>
        function getRandomColor() {
            const letters = '0123456789ABCDEF';
            let color = '#';
            for (let i = 0; i < 6; i++) {
                color += letters[Math.floor(Math.random() * 16)];
            }
            return color;
        }

        document.getElementById('js-button').onclick = function () {
            let randomColor = getRandomColor();
            document.body.style.backgroundColor = randomColor;
        }

    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

I got the getRandomColor() from ChatGPT. Interesting again how raw and mathy that works.

also again cool that document.getElementById() can just be replaced by document.body if that’s the object to be manipulated. No need to give the body an ID and get it that way etc.

Well that’s it again for today. Enjoy the weekend everyone 🥳

Top comments (0)