jqueryangularjsinput

Make html5 input[type=range] with many steps snap to the middle


I have an <input type=range> with a large number of allowed steps (in the range of 60,000).

Some of steps (for instance the mid-point) are more relevant and I would like a caret/snap to when the user moves close to them. How can I do that?

I am using the Angular and jQuery libraries.


Solution

  • There is a HTML5 feature that provides detent-snapping natively, using the list attribute and matching datalist element. Each element in the list becomes a detent point in the slider, with a tick-mark as well as snapping.

    <input type="range" value="0" min="0" max="60000" step="1" list="my-detents">
    
    <datalist id="my-detents">
      <option value="30000">
    </datalist>

    The datalist element can be placed anywhere in the HTML; it’s just defining the list (here named my-detents) for use by the input element.

    According to caniuse.com, as of July 2024, use of datalist with range inputs is supported by all major browsers.

    MDN mentions that Firefox only supports datalist for textual inputs, but range actually is also supported.