I'm calculating a hex color value from a set of HSL sliders.
When I change the sliders (which are bound to the HSL inputs via x-model), the hex input changes accordingly.
I am completely stuck when trying to get it to work backwards.
How can I change the HSL values when I type in a hex value in the bottom input?
https://codesandbox.io/s/agitated-williams-p54t1?file=/index.html
<body x-data="{h1: h1, s1: s1, l1: l1 }">
<input type="range" min="0" max="360" step="1" x-model="h1" />
<input type="number" min="0" max="360" x-model="h1"/>
<br>
<input type="range" min="0" max="100" step="1" x-model="s1" />
<input type="number" min="0" max="100" x-model="s1"/>
<br>
<input type="range" min="0" max="100" step="1" x-model="l1" />
<input type="number" min="0" max="100" x-model="l1"/>
<br>
<input type="text" id="hex1" x-bind:value="hslToHex(h1, s1, l1)" />
<input type="color" id="hex1" x-bind:value="hslToHex(h1, s1, l1)" />
</body>
<script>
var h1 = 50;
var s1 = 50;
var l1 = 50;
function hslToHex(h, s, l) {
l /= 100;
const a = s * Math.min(l, 1 - l) / 100;
const f = n => {
const k = (n + h / 30) % 12;
const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
return Math.round(255 * color).toString(16).padStart(2, '0'); // convert to Hex and prefix "0" if needed
};
return myHex = `#${f(0)}${f(8)}${f(4)}`;
};
</script>