Reputation: 938
I want to see the color being changed while I am changing it. I do not want to click somewhere else to see the results.
Like in inspect element, we can change the color and watch it live.
How is it being changed and how to do this with JavaScript and the DOM?
I tried addEventListener("mousemove")
, addEventListener("mousedown")
, and addEventListener("change")
.
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">
As you can see in my sample code, the color is not changing in live mode when I am changing the color in the color picker. After changing the color, I have to click anywhere else and then the color changes.
I want it to behave like in the gif above, I want to make color changes and see the changes at the same time.
Upvotes: 6
Views: 4460
Reputation: 21881
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
andchange
.input
is fired on the<input>
element every time the color changes. Thechange
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 itsvalue
.
(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">
Upvotes: 10