Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to precisely find thumb position of input [type="range"]?

Tags:

css

range

slider

The idea was to put a tooltip with value related to slider. I thought initially to accomplish that task by using css grid. CSS provides you with grid of any size, 10 or 1000 cols, doesn't matter. By utilizing grid functionality, we can align out tooltip as we wish. What we really get is:

thumb is unstable

Thumb position is sort of unpredictable. It seems that it is being offset, and the direction of that offset is dependent on whether input value is in the left or right part of slider.

Note: default thumb behaves exactly the same way. I mean, shape of thumb is not of concern.

So, how does html calculate position of thumb based on its value?

like image 429
ogostos Avatar asked Dec 19 '22 01:12

ogostos


1 Answers

For anyone else stumbling upon this problem, the issue is that the first and last position of thumb are offset by half the width of thumb. Because of this, all of the other positions are slightly offset to compensate for the first and last one.

One simple solution for this is to normalize the thumb position between actual first and last thumb positions which are actually 0 + halfThumb and width - halfThumb respectively.

To normalize, we can use the formula recommended in this answer.

So the left offset of absolutely positioned element in px would be:

const left = (((value - minValue) / (valueMax - valueMin)) * ((totalInputWidth - thumbHalfWidth) - thumbHalfWidth)) + thumbHalfWidth;

Where

value is actual input value.

minValue is actual minimum value for input.

maxValue is actual maximum value for input.

thumbHalfWidth is half of the width of thumb used for slider drag.

totalInputWidth is width of input element in pixels.

like image 170
ibrcic Avatar answered Jan 07 '23 07:01

ibrcic