How to scroll input type="range" by values from datalist

Viewed 42

I read that input type="range" supports the attribute list. So I have the following example:

<input type="range" list="values">
<datalist id="values">
    <option value="0">
    <option value="30">
    <option value="40">
    <option value="60">
    <option value="100">
</datalist>

I need to scroll only by the specified values the same as I specified a step. That is after 0 I need to jump to 30 when scrolling, then to 40 and so on. But I still can scroll by all possible values which are available by default i.e. 0, 1, 2, 3 etc (and I just feel snapping on the positions of the specified values).

In other words, I need input type="range" with "float" or "dynamic" step depending on the values from the list (30-0=30, 40-30=10, 60-40=20 etc.).

Is that possible with this type of input?

1 Answers

Natively in HTML you will not be able to force a range input to irregular, predefined steps. There is a step attribute for this type of input, however this allows for setting evenly spaced, predefined steps.

JavaScript can add this type of functionality, and how specific you get with your irregular spacing can vary pretty widely.

For this example, I kept it simple. The script gets a list from your values datalist and then whenever the input is changed, it finds the closest value and snaps to that instead.

let steps = [];
document.querySelectorAll("#values option").forEach(o => {
  steps.push(o.value);
});

document.querySelector("#slider").addEventListener("change", e => {
  steps.forEach((v, i) => {
    if(e.target.value <= parseFloat(v) && !steps.includes(e.target.value)) {
      e.target.value = (i > 0) ? ((parseFloat(v)-e.target.value) < (parseFloat(v)-parseFloat(steps[i-1]))/2) ? v : steps[i-1] : v;
    }
  });
});
<input id="slider" type="range" list="values" value="40" style="width: 400px;">
<datalist id="values">
    <option value="0">
    <option value="30">
    <option value="40">
    <option value="60">
    <option value="100">
</datalist>

Related