Aidan Young
Aidan Young

Reputation: 614

Javascript set variable value to html color picker hex value

I currently have a project with an html color picker. I also have a variable called color declared using JavaScript. What I'm wondering is how can I set the variable color constantly to the hex value of the color picker. For example, if I change the color picker to blue, the variable color will be set to #009DFF (Hex value for the blue color)

How can this be done?

<input
        type="color"
        value="#ff0000"
        style="border:3px solid #222; border-radius: 6px; "
  
      />
      
      <script>
      let color = 5;
      document.write (color);
      </script>

Fiddle: https://jsfiddle.net/AidanYoung/pjw1mzL3/2/

Upvotes: 1

Views: 1233

Answers (3)

Sercan
Sercan

Reputation: 5081

You can do it using the onchange event handler of the color picker object.

var colorCode;

function colorPickerEventHandler(value){
    colorCode= value;
    alert(colorCode);
    console.log(colorCode);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <p>
        <label for="color-picker">First Color Picker: </label>
        <input onchange="colorPickerEventHandler(this.value)" id="color-picker" type="color" value="#000000"/>
    </p>
</body>
</html>

Upvotes: 1

skara9
skara9

Reputation: 4194

I'm assuming you want to update the text next to the color picker every time it is changed.

First of all, the code in your script tag will be executed only once. It won't update live unless you provide the functionality.

Second, document.write will add the color value to your document, so even if you called it several times, you will end up with your page looking like 5#ff0000#f932a2#bb7d3e....

If you want to call a function whenever your color picker's value changes, use either the oninput or the onchange attribute on your input to call a function in your javascript.

Then, in the function, select a specific element from your DOM to change its value.

function updateColorText(colorText) {
  document.getElementById("color-text").innerText = colorText;
}
<input
    type="color"
    value="#ff0000"
    style="border:3px solid #222; border-radius: 6px;"
    oninput="updateColorText(this.value)"
/>
<span id="color-text"></span>

I recommend looking into the input event, change event and reading up on JavaScript event handling in general.

Upvotes: 4

LovingGarlic
LovingGarlic

Reputation: 185

I would put an id on the color input, then use document.getElementById to access it in the javascript to get the value out. Something like this:

<input
  type="color"
  value="#ff0000"
  style="border:3px solid #222; border-radius: 6px;"
  id="colorPicker"
/>
      
<script>
  let color = document.getElementById("colorPicker").value;
  console.log(color);
</script>

Upvotes: 0

Related Questions