Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the new value of HTML colorpicker when it changes?

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.

like image 602
Abby Avatar asked Jun 13 '18 12:06

Abby


2 Answers

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">
like image 137
cнŝdk Avatar answered Nov 15 '22 11:11

cнŝdk


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.

like image 21
Imran Rafiq Rather Avatar answered Nov 15 '22 10:11

Imran Rafiq Rather