An HTML color picker is an input element that allows users to select a color
visually or by entering a color code. It is created using the <input type="color">
element in HTML. This input provides a color swatch UI in
supported browsers, letting users pick a color and then returning the color
value in hexadecimal format (e.g., #ff0000 for red).
Basic Usage
The simplest HTML color picker can be created with this code:
html
<input type="color" />
Setting a Default Color
You can specify a default color with the value
attribute in 7-character
hexadecimal notation:
html
<input type="color" value="#ff0000" />
This sets the initial color to red.
Interacting with Color Changes Using JavaScript
You can listen to the input
and change
events on the color input to react
to color selections:
- The
input
event fires every time the user picks a new color while the picker is open. - The
change
event fires when the user closes the color picker after selecting a color.
Example JavaScript to update the color of page elements live:
js
const colorPicker = document.querySelector('input[type="color"]');
colorPicker.addEventListener('input', function(event) {
document.body.style.backgroundColor = event.target.value;
});
Browser Behavior
- If a browser does not support the color picker interface, it shows a text input that requires a valid hexadecimal color.
- The value format is always a hexadecimal string starting with "#" followed by 6 hex digits.
Uses and Advantages
- Great for letting users select and customize colors in web forms.
- The native color picker UI makes color selection intuitive without external libraries.
- Color values can be directly used in CSS styles.
There are also online tools called "color pickers" that allow picking colors
visually and converting between formats like HEX, RGB, HSL, which can be handy
when designing HTML/CSS color schemes. This HTML5 <input type="color">
element is supported widely in modern browsers and is a simple built-in
solution for color selection in web development.