|
| 1 | +const palette = document.querySelector('.palette'); |
| 2 | +const generateButton = document.getElementById('generateButton'); |
| 3 | + |
| 4 | +// Generate a random color in hex format (#RRGGBB) |
| 5 | +function getRandomColor() { |
| 6 | + const letters = '0123456789ABCDEF'; |
| 7 | + let color = '#'; |
| 8 | + for (let i = 0; i < 6; i++) { |
| 9 | + color += letters[Math.floor(Math.random() * 16)]; |
| 10 | + } |
| 11 | + return color; |
| 12 | +} |
| 13 | + |
| 14 | +// Create and append a color card to the palette |
| 15 | +function createColorCard() { |
| 16 | + const colorCard = document.createElement('div'); |
| 17 | + colorCard.classList.add('color-card'); |
| 18 | + const hexCode = getRandomColor(); |
| 19 | + colorCard.style.backgroundColor = hexCode; |
| 20 | + colorCard.innerHTML = ` |
| 21 | + <div class="hex-code">${hexCode}</div> |
| 22 | + `; |
| 23 | + palette.appendChild(colorCard); |
| 24 | + |
| 25 | + // Add click event to copy hex code to clipboard |
| 26 | + colorCard.addEventListener('click', () => { |
| 27 | + const tempInput = document.createElement('input'); |
| 28 | + tempInput.value = hexCode; |
| 29 | + document.body.appendChild(tempInput); |
| 30 | + tempInput.select(); |
| 31 | + document.execCommand('copy'); |
| 32 | + document.body.removeChild(tempInput); |
| 33 | + alert(`Hex code ${hexCode} copied to clipboard!`); |
| 34 | + }); |
| 35 | +} |
| 36 | + |
| 37 | +// Generate a random color palette with a specified number of colors |
| 38 | +function generatePalette(numColors) { |
| 39 | + palette.innerHTML = ''; // Clear existing colors |
| 40 | + for (let i = 0; i < numColors; i++) { |
| 41 | + createColorCard(); |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +// Event listener for the "Generate Colors" button |
| 46 | +generateButton.addEventListener('click', () => { |
| 47 | + const numColors = Math.floor(Math.random() * 4 + 1) * 2 * 2; // 10, 12, 14, or 16 colors |
| 48 | + generatePalette(numColors); |
| 49 | +}); |
| 50 | + |
| 51 | +// Initial palette generation |
| 52 | +generatePalette(10); // You can start with any initial number of colors |
0 commit comments