JSFiddle - React, Tailwind, and code Playground

by musicreader

HTML

<button id="toggleButton">Toggle Background/Text Color</button>

<div id="colorContainer"></div>

<script>
    const colors = [
        "#008000", "#FFC300", "#FF5733", "#900C3F", "#FF00FF", "#4B0082", 
        "#32CD32", "#4169E1", "#B8860B", "#2F4F4F","#C70039", "#6B8E23", "#8B008B", "#BC8F8F", "#DEB887", "#BA55D3", "#708090", "#A9A9A9"
    ];

    let toggleState = false;  // Initial state: background color on boxes

    const colorContainer = document.getElementById('colorContainer');

    // Function to create the color boxes dynamically
    function createColorBoxes() {
        colorContainer.innerHTML = ''; // Clear existing boxes

        colors.forEach(color => {
            const div = document.createElement('div');
            div.className = 'color-box';
            div.style.backgroundColor = toggleState ? 'white' : color;
            div.style.color = toggleState ? color : 'white';
            div.textContent = color;
            colorContainer.appendChild(div);
        });
    }

    // Initial creation of color boxes
    createColorBoxes();

    // Toggle button event listener
    document.getElementById('toggleButton').addEventListener('click', function() {
        toggleState = !toggleState;  // Toggle the state
        createColorBoxes();  // Recreate the boxes with the updated styles
    });
</script>

CSS

body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            color: #333;
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
        }
        .color-box {
            width: 100px;
            height: 25px;
            display: inline-block;
            margin: 10px;
            text-align: center;
            line-height: 25px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
        }
        button {
            display: block;
            margin: 20px auto;
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }