Color Picker and Input Hex Value, Native HTML and JS

When you type a valid HEX code in the text input, the color picker automatically updates to show that color.When you pick a color using the color picker, the HEX text input updates to show the corresponding HEX code.

Simple.


<style>  input[type="text"] {    padding: 5px;    font-size: 16px;    width: 150px;    text-align: center;    margin-bottom: 10px;  }
 input[type="color"] {    width: 50px;    height: 40px;    border: none;    cursor: pointer;  }</style>

<input type="text" id="hexInput" maxlength="7">  <br>  <input type="color" id="colorPicker">

<script>
  const colorPicker = document.getElementById("colorPicker");
  const hexInput = document.getElementById("hexInput");
  function expandShortHex(hex) {
    return "#" + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3];
  }
  colorPicker.value = "#ff5733";
  hexInput.value = colorPicker.value.toUpperCase();
  hexInput.addEventListener("input", () => {
    const inputVal = hexInput.value.trim();
    let validFullHex = null;

    if (/^#([0-9A-Fa-f]{3})$/.test(inputVal)) {
      validFullHex = expandShortHex(inputVal).toUpperCase();
    } else if (/^#([0-9A-Fa-f]{6})$/.test(inputVal)) {
      validFullHex = inputVal.toUpperCase();
    }

    if (validFullHex) {
      colorPicker.value = validFullHex;
    }
  });
  colorPicker.addEventListener("input", () => {
    const fullHex = colorPicker.value.toUpperCase();
    hexInput.value = fullHex;
  });
</script>