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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs