Write a custom color picker in HTML, CSS, and JS (without using input:color)
- User
Write a custom color picker in HTML, CSS, and JS (without using input:color)
- Assistant
Write a custom color picker in HTML, CSS, and JS (without using input:color)
Creating a custom color picker using HTML, CSS, and JavaScript involves building a user interface that allows users to select colors through various interactive elements. Below is a step-by-step guide to creating a basic yet functional custom color picker without relying on the native <input type="color"> element.
Our custom color picker will consist of the following components:
We'll structure our color picker with div elements representing the color palette, hue slider, color display, and hex input field.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Custom Color Picker</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="color-picker">
<div class="palette-container">
<div class="palette" id="palette">
<div class="selector" id="palette-selector"></div>
</div>
<div class="hue-slider" id="hue-slider">
<div class="hue-selector" id="hue-selector"></div>
</div>
</div>
<div class="selected-color" id="selected-color"></div>
<input type="text" id="hex-value" readonly />
</div>
<script src="script.js"></script>
</body>
</html>
We'll style the color picker components to make them visually appealing and functional.
/* styles.css */
body {
font-family: Arial, sans-serif;
display: flex;
height: 100vh;
align-items: center;
justify-content: center;
background-color: #f0f0f0;
}
.color-picker {
display: flex;
flex-direction: column;
align-items: center;
}
.palette-container {
display: flex;
margin-bottom: 20px;
}
.palette {
position: relative;
width: 300px;
height: 300px;
background: linear-gradient(to right, #fff, rgba(255,255,255,0)),
linear-gradient(to top, #000, rgba(0,0,0,0));
cursor: crosshair;
}
.hue-slider {
position: relative;
width: 30px;
height: 300px;
margin-left: 10px;
background: linear-gradient(to top,
red,
yellow,
lime,
aqua,
blue,
magenta,
red
);
cursor: pointer;
}
.selector {
position: absolute;
width: 12px;
height: 12px;
border: 2px solid #fff;
border-radius: 50%;
box-shadow: 0 0 2px rgba(0,0,0,0.7);
transform: translate(-6px, -6px);
pointer-events: none;
}
.hue-selector {
position: absolute;
width: 100%;
height: 4px;
background: #fff;
border: 1px solid #000;
border-radius: 2px;
transform: translateY(-2px);
}
.selected-color {
width: 100px;
height: 100px;
border: 1px solid #ccc;
margin-bottom: 10px;
}
#hex-value {
width: 100px;
padding: 5px;
text-align: center;
}
We'll handle user interactions such as clicking and dragging on the palette and hue slider to update the selected color.
HTML Structure:
.palette): This is the area where users can select the saturation and brightness. It has two background gradients:
.hue-slider): A vertical gradient representing all hues from 0 to 360 degrees..selector and .hue-selector): Visual indicators showing the current selection on the palette and hue slider.CSS Styling:
.palette uses two linear gradients to represent saturation and brightness..hue-slider uses a continuous hue gradient..selected-color div displays the currently selected color, and the #hex-value input shows its hex code.JavaScript Functionality:
init): Sets the initial color based on default HSV values and updates the hex input.mousedown and mousemove, updates saturation and brightness based on cursor position within the palette. Updates the selector's position and the selected color.mousedown and mousemove, updates the hue based on cursor position within the hue slider. Adjusts the palette's background to reflect changes in hue and updates the selected color.hsvToRgb and rgbToHex): Converts HSV values to RGB, then to hexadecimal for display purposes..selected-color and updates the hex input field to reflect the current selection.While the above implementation provides a basic custom color picker, here are some enhancements and best practices to consider:
touchstart, touchmove, touchend) alongside mouse events.For your convenience, here's a complete example you can run directly. Create three files: index.html, styles.css, and script.js, and paste the respective code into each.
index.html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Custom Color Picker</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="color-picker">
<div class="palette-container">
<div class="palette" id="palette">
<div class="selector" id="palette-selector"></div>
</div>
<div class="hue-slider" id="hue-slider">
<div class="hue-selector" id="hue-selector"></div>
</div>
</div>
<div class="selected-color" id="selected-color"></div>
<input type="text" id="hex-value" readonly />
</div>
<script src="script.js"></script>
</body>
</html>
styles.css/* styles.css */
body {
font-family: Arial, sans-serif;
display: flex;
height: 100vh;
align-items: center;
justify-content: center;
background-color: #f0f0f0;
}
.color-picker {
display: flex;
flex-direction: column;
align-items: center;
}
.palette-container {
display: flex;
margin-bottom: 20px;
}
.palette {
position: relative;
width: 300px;
height: 300px;
background: linear-gradient(to right, #fff, rgba(255,255,255,0)),
linear-gradient(to top, #000, rgba(0,0,0,0));
cursor: crosshair;
}
.hue-slider {
position: relative;
width: 30px;
height: 300px;
margin-left: 10px;
background: linear-gradient(to top,
red,
yellow,
lime,
aqua,
blue,
magenta,
red
);
cursor: pointer;
}
.selector {
position: absolute;
width: 12px;
height: 12px;
border: 2px solid #fff;
border-radius: 50%;
box-shadow: 0 0 2px rgba(0,0,0,0.7);
transform: translate(-6px, -6px);
pointer-events: none;
}
.hue-selector {
position: absolute;
width: 100%;
height: 4px;
background: #fff;
border: 1px solid #000;
border-radius: 2px;
transform: translateY(-2px);
}
.selected-color {
width: 100px;
height: 100px;
border: 1px solid #ccc;
margin-bottom: 10px;
}
#hex-value {
width: 100px;
padding: 5px;
text-align: center;
}
script.jsHere's a JSFiddle link where you can see the color picker in action. (Note: As of my knowledge cutoff in September 2021, direct links are not possible. Please copy the above code into your local environment or an online code editor like CodePen, JSFiddle, or JSBin to test it.)
This guide provides a foundational custom color picker using HTML, CSS, and JavaScript. You can enhance it further by adding features like keyboard accessibility, touch support, color opacity selection, displaying RGB/HSL values, and more. Building a custom color picker not only gives you control over its appearance and functionality but also allows for a more seamless integration with your application's design and requirements.
Not yet included in a published release.
// script.js
const palette = document.getElementById('palette');
const paletteSelector = document.getElementById('palette-selector');
const hueSlider = document.getElementById('hue-slider');
const hueSelector = document.getElementById('hue-selector');
const selectedColor = document.getElementById('selected-color');
const hexValue = document.getElementById('hex-value');
let hue = 0;
let saturation = 100;
let brightness = 100;
// Initialize the picker
function init() {
updateColor();
hexValue.value = rgbToHex(selectedColor.style.backgroundColor);
}
// Convert RGB to Hex
function rgbToHex(rgb) {
const result = rgb.match(/\d+/g);
if (!result) return '#FFFFFF';
return "#" + result.slice(0, 3).map(x => {
const hex = parseInt(x).toString(16);
return hex.length === 1 ? '0' + hex : hex;
}).join('');
}
// Update the displayed color
function updateColor() {
const rgb = hsvToRgb(hue, saturation, brightness);
const hex = rgbToHex(`rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`);
selectedColor.style.backgroundColor = `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`;
hexValue.value = hex;
}
// Convert HSV to RGB
function hsvToRgb(h, s, v) {
s /= 100;
v /= 100;
let c = v * s;
let x = c * (1 - Math.abs((h / 60) % 2 - 1));
let m = v - c;
let r = 0, g = 0, b = 0;
if (0 <= h && h < 60) { r = c; g = x; b = 0; }
else if (60 <= h && h < 120) { r = x; g = c; b = 0; }
else if (120 <= h && h < 180) { r = 0; g = c; b = x; }
else if (180 <= h && h < 240) { r = 0; g = x; b = c; }
else if (240 <= h && h < 300) { r = x; g = 0; b = c; }
else if (300 <= h && h < 360) { r = c; g = 0; b = x; }
return {
r: Math.round((r + m) * 255),
g: Math.round((g + m) * 255),
b: Math.round((b + m) * 255)
};
}
// Handle palette interactions
function handlePaletteEvent(e) {
const rect = palette.getBoundingClientRect();
let x = e.clientX - rect.left;
let y = e.clientY - rect.top;
x = Math.max(0, Math.min(x, rect.width));
y = Math.max(0, Math.min(y, rect.height));
saturation = (x / rect.width) * 100;
brightness = 100 - (y / rect.height) * 100;
paletteSelector.style.left = `${x}px`;
paletteSelector.style.top = `${y}px`;
updateColor();
}
// Handle hue slider interactions
function handleHueEvent(e) {
const rect = hueSlider.getBoundingClientRect();
let y = e.clientY - rect.top;
y = Math.max(0, Math.min(y, rect.height));
hue = 360 - (y / rect.height) * 360;
hueSelector.style.top = `${y}px`;
// Update palette background based on hue
palette.style.background = `
linear-gradient(to right, #fff, rgba(255,255,255,0)),
linear-gradient(to top, #000, rgba(0,0,0,0)),
linear-gradient(to right, hsl(${hue}, 100%, 50%), hsl(${hue}, 100%, 50%))
`;
updateColor();
}
// Mouse event handlers
let isDraggingPalette = false;
let isDraggingHue = false;
// Palette Mouse Events
palette.addEventListener('mousedown', (e) => {
isDraggingPalette = true;
handlePaletteEvent(e);
});
document.addEventListener('mousemove', (e) => {
if (isDraggingPalette) {
handlePaletteEvent(e);
}
if (isDraggingHue) {
handleHueEvent(e);
}
});
document.addEventListener('mouseup', () => {
isDraggingPalette = false;
isDraggingHue = false;
});
// Hue Slider Mouse Events
hueSlider.addEventListener('mousedown', (e) => {
isDraggingHue = true;
handleHueEvent(e);
});
// Initialize picker on load
window.onload = init;
// script.js
const palette = document.getElementById('palette');
const paletteSelector = document.getElementById('palette-selector');
const hueSlider = document.getElementById('hue-slider');
const hueSelector = document.getElementById('hue-selector');
const selectedColor = document.getElementById('selected-color');
const hexValue = document.getElementById('hex-value');
let hue = 0;
let saturation = 100;
let brightness = 100;
// Initialize the picker
function init() {
updateColor();
hexValue.value = rgbToHex(selectedColor.style.backgroundColor);
}
// Convert RGB to Hex
function rgbToHex(rgb) {
const result = rgb.match(/\d+/g);
if (!result) return '#FFFFFF';
return "#" + result.slice(0, 3).map(x => {
const hex = parseInt(x).toString(16);
return hex.length === 1 ? '0' + hex : hex;
}).join('');
}
// Update the displayed color
function updateColor() {
const rgb = hsvToRgb(hue, saturation, brightness);
const hex = rgbToHex(`rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`);
selectedColor.style.backgroundColor = `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`;
hexValue.value = hex;
}
// Convert HSV to RGB
function hsvToRgb(h, s, v) {
s /= 100;
v /= 100;
let c = v * s;
let x = c * (1 - Math.abs((h / 60) % 2 - 1));
let m = v - c;
let r = 0, g = 0, b = 0;
if (0 <= h && h < 60) { r = c; g = x; b = 0; }
else if (60 <= h && h < 120) { r = x; g = c; b = 0; }
else if (120 <= h && h < 180) { r = 0; g = c; b = x; }
else if (180 <= h && h < 240) { r = 0; g = x; b = c; }
else if (240 <= h && h < 300) { r = x; g = 0; b = c; }
else if (300 <= h && h < 360) { r = c; g = 0; b = x; }
return {
r: Math.round((r + m) * 255),
g: Math.round((g + m) * 255),
b: Math.round((b + m) * 255)
};
}
// Handle palette interactions
function handlePaletteEvent(e) {
const rect = palette.getBoundingClientRect();
let x = e.clientX - rect.left;
let y = e.clientY - rect.top;
x = Math.max(0, Math.min(x, rect.width));
y = Math.max(0, Math.min(y, rect.height));
saturation = (x / rect.width) * 100;
brightness = 100 - (y / rect.height) * 100;
paletteSelector.style.left = `${x}px`;
paletteSelector.style.top = `${y}px`;
updateColor();
}
// Handle hue slider interactions
function handleHueEvent(e) {
const rect = hueSlider.getBoundingClientRect();
let y = e.clientY - rect.top;
y = Math.max(0, Math.min(y, rect.height));
hue = 360 - (y / rect.height) * 360;
hueSelector.style.top = `${y}px`;
// Update palette background based on hue
palette.style.background = `
linear-gradient(to right, #fff, rgba(255,255,255,0)),
linear-gradient(to top, #000, rgba(0,0,0,0)),
linear-gradient(to right, hsl(${hue}, 100%, 50%), hsl(${hue}, 100%, 50%))
`;
updateColor();
}
// Mouse event handlers
let isDraggingPalette = false;
let isDraggingHue = false;
// Palette Mouse Events
palette.addEventListener('mousedown', (e) => {
isDraggingPalette = true;
handlePaletteEvent(e);
});
document.addEventListener('mousemove', (e) => {
if (isDraggingPalette) {
handlePaletteEvent(e);
}
if (isDraggingHue) {
handleHueEvent(e);
}
});
document.addEventListener('mouseup', () => {
isDraggingPalette = false;
isDraggingHue = false;
});
// Hue Slider Mouse Events
hueSlider.addEventListener('mousedown', (e) => {
isDraggingHue = true;
handleHueEvent(e);
});
// Initialize picker on load
window.onload = init;