Get the value of input type color onchange
Get the value of input type color onchange event in javascript
Yogesh 15 Oct, 2020 8382
The onchange event is not working in Input type color(input[type="color"]). So we'll use input event instead of onchange to apply the changes.
Html syntax
<input type="color" id="color" />
Javascript
First, we will fetch the Input element by ID.
let color = document.getElementById('color');
Next, we will trigger the event. The in-built input type color will populate a popup like another browser window/iframe. When we change the color it will not reflect immidiatly using the onchange event listner.
To get the value using onchange either you've to click outside of the box or you've to press the select button depends on browser.
So, we will use the input eventlistner instead of onchange event. The difference is... oninput event occurs when the text content of an element is changed through the user interface. **onchange ** occurs when checked state, selection or content of an element changed by the user.
input event js
color.addEventListener('input', function(e) {
alert(this.value);
The above snippet will return the value of the color when user drag in the input type color box.
Demo
Chrome
Firefox
Also, you can customise the color & theme according to your need like in cover image. The demo code HTML
<input type="color" id="color" />
<input type="text" id="clr_input" value="#000000"/>
<label id="clr_lbl">#000000</label>
<span id="clr_span"></span>
Javascript
let color = document.getElementById('color');
color.addEventListener('input', function(e) {
clr_lbl.innerHTML = this.value;
clr_input.value = this.value;
clr_lbl.style.color = this.value;
clr_span.style.background = this.value;
});
If you're using Vue.js or React js then the events will be... Vue js Set the v-model and data
data: {
return { color: '' }
}
Next, create the input color tag
<input id="color" v-model="color" @input="handleChange" type="color" />
In above snippet we will use the method handleChange onInput. We will use @input or v-on:input to trigger the event. Vue js method to handle the colro change.
methods: {
handleChange() {
console.log(this.color);
}
}
React js Set the state
constructor() {
this.state = {color: ''}
}
Hml
<input type="text" value={this.state.color} onChange={this.handleChange} />
React method to handle the change event.
handleChange(event) { this.setState({color: event.target.color}); }