I'm making a slider from scratch and I'm having an issue with the absolute positioning which has to be relative to the viewport (whenever the window height changes). Basically the slider has a bar and a button (to slide) and I wrote code to get the relative button position to the bar:
const getRelativeCoordinates = (event, referenceElement) => {
const position = {
x: event.pageX,
y: event.pageY
};
const offset = {
left: referenceElement.offsetLeft,
top: referenceElement.offsetTop
};
return {
x: position.x - offset.left,
y: position.y - offset.top,
};
}
and I wrote code to know after a cursor slide where the button would change his position and what percentage 1-100 actually is:
const handleSlider = (e) => {
const sliderBar = document.getElementById('slider-bar')
const sliderBtn = document.getElementById('slider-button')
const sliderHeight = parseInt(sliderBar.getBoundingClientRect().height) - sliderBarOffsetY
const cursorY = getRelativeCoordinates(e, document.getElementById('slider-bar')).y
let slidingPerc = ((sliderHeight - cursorY) / sliderHeight) * 100
if (slidingPerc > 100) slidingPerc = 100
else if (slidingPerc < 0) slidingPerc = 0
let barPerc = sliderBarMaxY - ((slidingPerc * (sliderBarMaxY - sliderBarMinY)) / 100)
return {
barPerc,
slidingPerc
}
}
The problem is that sliderBarMaxY and sliderBarMinY (83 and 9) are constants of max and min values of the button absolute top position in percentage (83% and 9%). These values changing the viewport height would not work anymore and if I try to change them by window.innerHeight (83 : 460 = x : innerHeight) gives an offset-error (in my case of 17)