When the user chose a colour in the colour picker. How can I get the colour value and use the colour value later in the code?
<!DOCTYPE HTML>
<HTML>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
</head>
<body>
<label for="color">Please chose a color </label>
<input type="color" id="color" name="color2">
<script>
let userColor= document.querySelector("#color").value
console.log(userColor)
</script>
</body>
</html>
Get the value with onchange event:
document.querySelector("#color").onchange = e => {
console.log(e.target.value)
}
<label for="color">Please chose a color </label>
<input type="color" id="color" name="color2">
You Should add a change event listener to color input like this
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
</head>
<body>
<label for="color">Please chose a color </label>
<input type="color" id="color" name="color2">
<script>
let userColor= document.querySelector("#color");
userColor.addEventListener("change",(e) => {
console.log(e.target.value)
})
</script>
</body>
</html>
You need to use addEventListener, so then you can call to one function every time this cganges:
<body>
<label for="color">Please chose a color </label>
<input type="color" id="color" name="color2">
<button onclick="whatColor()">ASDASD</button>
<script>
let color = "";
let userColor = document.querySelector("#color");
userColor.addEventListener("change", myFunction);
function myFunction() {
console.log(userColor.value);
color = userColor.value;
}
function whatColor() {
console.log(color);
}
</script>
</body>
This will call myFunction every time your input value changes. For making this write something, you will need to change the color, for make sure you change color, you should click outside the input when you choose your color.
You can also use userColor.addEventListener("input", myFunction); who will print every time you click on input