I am trying to display the value of a range item centered above the thumb. This works quite well by reading out the value and positioning the element above the range element as a percentage of its clientWidth
.
There is however a growing offset away from the middle (see pictures) which causes the value not to be centered on the thumb. I am convinced that this is caused because the thumb actually moves less than the clientWidth
because of the size of the thumb itself and maybe some room around the track.
How do I take this into account?
The JSFiddle can be found here: https://jsfiddle.net/jd4kncuk/
var myRange = document.querySelector('#myRange');
var myValue = document.querySelector('#myValue');
var off = myRange.clientWidth / (parseInt(myRange.max) - parseInt(myRange.min));
var px = ((myRange.valueAsNumber - parseInt(myRange.min)) * off) - (myValue.clientWidth / 2);
myValue.style.left = px + 'px';
myValue.style.top = -myRange.offsetHeight - 5 + 'px';
myValue.innerHTML = myRange.value;
myRange.oninput = function() {
let px = ((myRange.valueAsNumber - parseInt(myRange.min)) * off) - (myValue.clientWidth / 2);
myValue.innerHTML = myRange.value;
myValue.style.left = px + 'px';
};
<div style="position:relative; margin:auto; width:90%; margin-top:80px;">
<output style="position:absolute; min-width:100px; text-align: center;" id="myValue"></output>
<input type="range" id="myRange" min="0" max="200" step="5" style="width:80%" value="80">
</div>