DEV Community

Cover image for Daily Code 53 | 🎨 Interactive Color Changing Grid
Gregor Schafroth
Gregor Schafroth

Posted on

Daily Code 53 | 🎨 Interactive Color Changing Grid

Hi everyone! Time for another 🟨 JavaScript Dom coding challenge. Let’s go! As usual first the exercise (I got from ChatGPT) and below my code :)

Exercise: Interactive Color Changing Grid

Objective: Create a web page with a grid of squares. Each square changes color when clicked.

Requirements:

  1. HTML Structure: Create a simple HTML page with a div element designated to contain the grid.
  2. CSS Styling: Style the squares and the grid container for a clean, grid-like appearance.
  3. JavaScript Logic:
    • Dynamically generate a grid of squares (e.g., 10x10) using JavaScript.
    • Each square should be a div element.
    • Attach a click event listener to each square.
    • When a square is clicked, change its background color to a random color.

Advanced Challenges (Optional):

  1. Reset Button: Add a button to reset all squares to their original color.
  2. Grid Size Selector: Allow the user to specify the size of the grid (e.g., 5x5, 10x10, 20x20).
  3. Color Selector: Let the user choose a color or set of colors to be used when squares are clicked.
  4. Save and Load State: Implement functionality to save the current state of the grid and load it later.

Learning Outcomes:

  • DOM manipulation using JavaScript.
  • Event handling in JavaScript.
  • Dynamic HTML element creation and styling.

This exercise will help you practice creating interactive web elements, handling user events, and dynamically modifying the DOM based on user interaction. Enjoy coding!

My Code

Ok honestly I struggled really quickly with this one. Could do neither html, css, nor JavaScript. But its also kind of complicated. A good inspiration for what I still have to learn.

The Solution

So here is how ChatGPT solved this

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exercise: Interactive Color Changing Grid</title>
    <style>
        .grid-container {
            display: grid;
            grid-template-columns: repeat(10, 1fr);
            /* Creates a 10x10 grid */
            grid-gap: 5px;
            /* Spacing between squares */
            width: 500px;
            /* Width of the grid */
            height: 500px;
            /* Height of the grid */
            margin: auto;
            /* Center the grid on the page */
            width: 90%;
            /* Adjust width to be a percentage of the screen */
            max-width: 500px;
            /* Maximum size */
            aspect-ratio: 1;
            /* Keeps the width and height the same */
        }

        .grid-square {
            background-color: #f0f0f0;
            /* Initial background color */
            width: 100%;
            /* Full width of the grid cell */
            height: 100%;
            /* Full height of the grid cell */
            transition: background-color 0.3s;
            /* Smooth transition for color change */
        }

        .reset-button {
            display: block;
            margin: 20px auto;
            /* Center the button */
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        .reset-button:hover {
            background-color: #0056b3;
            /* Darker shade on hover */
        }
    </style>
</head>

<body>
    <div class="grid-container" id="gridContainer">
        <!-- JavaScript will dynamically insert squares here -->
    </div>
    <button class="reset-button" id="resetButton">Reset Colors</button>
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const gridContainer = document.getElementById('gridContainer');
            const resetButton = document.getElementById('resetButton');

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

            // Function to create the grid
            function createGrid(size) {
                gridContainer.innerHTML = ''; // Clear any existing squares
                for (let i = 0; i < size * size; i++) {
                    const square = document.createElement('div');
                    square.classList.add('grid-square');
                    square.addEventListener('mouseover', () => {
                        square.style.backgroundColor = getRandomColor();
                    });
                    gridContainer.appendChild(square);
                }
            }

            // Function to reset the grid colors
            function resetGrid() {
                const squares = gridContainer.querySelectorAll('.grid-square');
                squares.forEach(square => {
                    square.style.backgroundColor = '#f0f0f0'; // Original color
                });
            }

            // Initialize the grid
            createGrid(10); // Creates a 10x10 grid

            // Add event listener to the reset button
            resetButton.addEventListener('click', resetGrid);
        });
    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

The result is pretty cool! 🎨

See you next time 🙋‍♂️

Top comments (0)