<body>
<style>
body {
position: relative;
}
.stop {
display: flex;
align-items: center;
position: absolute;
--input-width: 122px; /* estimated width of `hsl(360, 100%, 100%)` */
--button-width: 18px;
--width: calc(var(--input-width) + var(--button-width));
}
input {
margin: 0;
width: var(--input-width);
color: white;
background-color: black;
border: 1px solid white;
}
button.remove-color-stop {
margin: -2px 0 0 2px;
padding: 0;
font-size: 16px;
line-height: 16px;
color: white;
background-color: transparent;
border: none;
}
button.add-color-stop {
position: absolute;
top: 24px;
right: 0;
}
</style>
<script>
let colorStops = [];
function drawGradient() {
if (colorStops.length < 2)
return;
let steps = [];
colorStops.forEach((colorStop, i) => {
colorStop.container.style.setProperty("left", `clamp(0%, calc(100% * ${i} / ${colorStops.length - 1}), calc(100% - var(--width))`)
steps.push(colorStop.input.value);
});
document.body.style.setProperty("background-image", `linear-gradient(to right, ${steps.join(", ")})`);
localStorage.setItem("stops", JSON.stringify(steps));
}
function addColorInput(value) {
let index = colorStops.length;
let container = document.body.appendChild(document.createElement("div"));
container.className = "stop";
let input = container.appendChild(document.createElement("input"));
input.value = value || "hsl(0, 50%, 50%)";
input.addEventListener("input", drawGradient);
let deleteButton = container.appendChild(document.createElement("button"));
deleteButton.className = "remove-color-stop";
deleteButton.title = "Remove Color Stop";
deleteButton.textContent = "\u00d7"; // multiplication sign
deleteButton.addEventListener("click", (event) => {
container.remove();
colorStops.splice(index, 1);
drawGradient();
});
colorStops.push({container, input});
drawGradient();
}
try {
for (let stop of JSON.parse(localStorage.getItem("stops")))
addColorInput(stop);
} catch {
addColorInput();
addColorInput();
}
let addColorStopButton = document.body.appendChild(document.createElement("button"));
addColorStopButton.className = "add-color-stop";
addColorStopButton.textContent = "Add Color";
addColorStopButton.addEventListener("click", (event) => {
addColorInput(colorStops[colorStops.length - 1].input.value);
});
</script>