
HTML Color Picker
To create a color picker in HTML, you can use the <input>
element with the type
attribute set to "color"
. Here’s an example:
<input type="color" id="colorPicker">
In the above code, the <input>
element of type "color"
will render a color picker control. When a user clicks on the control, a color picker dialog will be displayed, allowing them to choose a color.
To retrieve the selected color using JavaScript, you can listen for the change
event on the <input>
element and access its value
property. Here’s an example:
<input type="color" id="colorPicker">
<script>
var colorPicker = document.getElementById('colorPicker');
colorPicker.addEventListener('change', function() {
var selectedColor = colorPicker.value;
console.log('Selected color: ' + selectedColor);
// Do something with the selected color
});
</script>
In the JavaScript code, we access the <input>
element using its id
attribute and attach a change
event listener to it. When the color selection changes, the event listener function will be executed. Inside the function, we retrieve the selected color using the value
property of the <input>
element.
You can use the selectedColor
value in your JavaScript code to apply the chosen color to other elements or perform any desired actions based on the selected color.