Home > Enterprise >  Javascript set variable value to html color picker hex value
Javascript set variable value to html color picker hex value

Time:12-16

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? Fiddle containing code: https://jsfiddle.net/AidanYoung/pjw1mzL3/2/

CodePudding user response:

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.

CodePudding user response:

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>

CodePudding user response:

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>

  • Related