I need a very important help, I have an input color with a color and a text field. How can I change the color of the input (color) using the text field.
I need a very important help, I have an input color with a color and a text field. How can I change the color of the input (color) using the text field.
A simple answer like the question:
In this code the only thing I did was to update the value of "input[type=color]"
using the events oncut
, onkeyup
, ... HTMLInputElement
.
I've added a few extra things.
var hexColorInput = document.getElementById('hex_input'),
colorSelector = document.getElementById('color_selector');
var updateHex ;
(updateHex = function () {
hexColorInput.value = colorSelector.value;
})();
colorSelector.addEventListener('input', updateHex);
function updateSelector() {
var val = hexColorInput.value;
// adiciona o '#'
if (val.charAt(0) !== '#') val = '#' + val;
// expande uma cor desse tamanho: fff
if (val.length === 4) {
var red = val.charAt(1);
red += red;
var green = val.charAt(2);
green += green;
var blue = val.charAt(3);
blue += blue;
val = '#' + red + green + blue;
}
colorSelector.value = val;
}
['cut', 'keyup', 'paste'].forEach(function(evt) {
hexColorInput.addEventListener(evt, updateSelector);
});
<input id="color_selector" type="color"/>
<input id="hex_input" type="text">
Waiting for event input
in text field.
Just grab the value of the text input and apply it as the value of the color field:
(function(){
var text = document.querySelector('input[type=text]'),
color = document.querySelector('input[type=color]');
text.addEventListener('input', function(){
color.value = this.value;
});
})();
<input type='text' placeholder='#RRGGBB'>
<input type='color'>