Color Picker Source Code
<!-- COLOR PICKER PROJECT -->
<!-- Features: HEX to RGB conversion, random colors, copy to clipboard -->
<!-- HTML STRUCTURE -->
<div class="container">
<h1>🎨 Color Picker</h1>
<div class="color-display" id="colorDisplay"></div>
<div class="color-info">
<p>HEX: <span id="hexValue">#667eea</span></p>
<p>RGB: <span id="rgbValue">rgb(102, 126, 234)</span></p>
</div>
<input type="color" id="colorInput" value="#667eea">
<button onclick="copyToClipboard('hex')">Copy HEX</button>
<button onclick="copyToClipboard('rgb')">Copy RGB</button>
<button onclick="randomColor()">Random</button>
</div>
<!-- KEY FUNCTIONS -->
// HEX to RGB Conversion using Regex
function hexToRgb(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
// Update Color Display
function updateColor(hex) {
colorDisplay.style.backgroundColor = hex;
hexValue.textContent = hex.toUpperCase();
const rgb = hexToRgb(hex);
rgbValue.textContent = `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`;
}
// Random Color Generator
function randomColor() {
const randomHex = '#' + Math.floor(Math.random() * 16777215)
.toString(16)
.padStart(6, '0');
colorInput.value = randomHex;
updateColor(randomHex);
}
// Copy to Clipboard
function copyToClipboard(type) {
const text = type === 'hex' ? hexValue.textContent : rgbValue.textContent;
navigator.clipboard.writeText(text).then(() => {
feedback.textContent = 'Copied to clipboard!';
setTimeout(() => feedback.textContent = '', 2000);
});
}
// Event Listener for input change
const colorInput = document.getElementById('colorInput');
colorInput.addEventListener('input', (e) => updateColor(e.target.value));
<!-- KEY CONCEPTS -->
// Regex: /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i extracts RGB from HEX
// parseInt(hex, 16): Converts hexadecimal to decimal
// Math.random(): Generates random value 0-1
// navigator.clipboard.writeText(): Copies text to clipboard
// padStart(): Ensures HEX color has leading zeros