admin管理员组

文章数量:1303335

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">

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.

Share Improve this question edited Sep 20, 2024 at 7:25 PeterJames 1,3533 gold badges11 silver badges21 bronze badges asked Feb 5, 2021 at 15:01 AltroAltro 9383 gold badges11 silver badges28 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 10

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">

本文标签: javascriptSee how the color is being changed with input typecolorStack Overflow