Skip to content
Advertisement

See how the color is being changed with input type=color

I want to see the color being changed whilst I am changing it, not after I click somewhere else so I see the results. Like in inspect element, we are changing color and watching live – how is it being changed and how to do the same with js dom? I tried addEventListener(“mousemove”), addEventListener(“mousedown”) and addEventListener(“change”)

enter image description here

document.getElementById("b").addEventListener("change",function(e){
  document.getElementById("a").style.backgroundColor = e.target.value;
})
#a {
  width: 100px;
  height: 100px;
  background-color: black;
}
<div id="a"></div>
<input type="color" id="b">

]2]2

As you can see on the code, it is not changing in live mode, I am changing and after changing I am clicking anywhere else and the the color is being changed, I want it like in the gif above, change and see the changes at the same time

Advertisement

Answer

change is only triggered when the dialogue is closed.
You want input instead:

Tracking color changes

As is the case with other <input> types, there are two events that can be used to detect changes to the color value: input and change. input is fired on the <input> element every time the color changes. The change event is fired when the user dismisses the color picker. In both cases, you can determine the new value of the element by looking at its value.

(Source: MDN | <input type="color"> -> Tracking color changes)

document.getElementById("b").addEventListener("input", function() {
  console.log(this.value);
  document.getElementById("a").style.backgroundColor = this.value;
})
#a {
  width: 100px;
  height: 100px;
  background-color: black;
}
<div id="a"></div>
<input type="color" id="b">
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement