I'm developing a web app that needs to change colour of HTML canvas
based on the values of colorpicker
.
I have a colorpicker
in HTML that I need to get value
from every time it updates.
<input type="color" value="#ff0800" id="color">
Currently, this is the code that is associated with the colorpicker
in my javascript file.
var backRGB = document.getElementById("color").value;
I am really not sure how this can be achieved.
I have tried other stack exchange question but none of them really meet my requirements so I would really appreciate if someone could show me how this can be achieved.
You just need to update the value of backRGB
variable when the colorpicker
value is changed.
To achieve that, you need to attach a handler to the onchange
event of your colorpicker
:
document.getElementById("color").onchange = function() {
backRGB = this.value;
}
Demo:
This is a working demo:
var backRGB = document.getElementById("color").value;
document.getElementById("color").onchange = function() {
backRGB = this.value;
console.log(backRGB);
}
<input type="color" value="#ff0800" id="color">
Adding to the answers already given, We can also attach oninput event handler instead of onchange event. This is another way we can monitor the color picker events from the user.
This event is similar to the onchange event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus, after the content has been changed. The other difference is that the onchange event also works on elements. Here is an example:
const backRGB = document.querySelector(".backRCB");
const color = document.querySelector(".color");
color.addEventListener("input",(event)=>{
backRGB.style.backgroundColor = color.value;
// You can also do it with the event object as event object holds the value of the current color
// backRGB.style.backgroundColor = event.target.value;
});
Hope that would be helpful to many users.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With