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 πŸ₯³

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Retry later
πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay