script.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. const targetColor = U.obs();
  2. const randomizeTargetColor = () => {
  3. targetColor.value = d3
  4. .hsl(Math.random() * 360, Math.random(), Math.random())
  5. .formatHex();
  6. };
  7. U.element("colorSelect", ({ randomButton }, form) => {
  8. U.field(form.elements.colorText, { obs: targetColor });
  9. U.field(form.elements.colorPicker, { obs: targetColor });
  10. U.form(form);
  11. randomButton.addEventListener("click", randomizeTargetColor);
  12. });
  13. randomizeTargetColor();
  14. targetColor.subscribe((hex, { previous }) => {
  15. const style = document.querySelector(":root").style;
  16. style.setProperty("--background", hex);
  17. style.setProperty("--highlight", getContrastingTextColor(hex));
  18. if (previous) {
  19. const prevButton = document.createElement("button");
  20. prevButton.innerText = previous;
  21. const { h, s, l } = d3.hsl(previous);
  22. prevButton.style = `
  23. color: ${getContrastingTextColor(previous)};
  24. --button-bg: ${previous};
  25. --button-bg-hover: ${d3.hsl(h, s, clamp(0.25, l * 1.25, 0.9)).formatHex()};
  26. `;
  27. prevButton.addEventListener("click", () => (targetColor.value = previous));
  28. document.getElementById("prevColors").prepend(prevButton);
  29. }
  30. });