personal-website/resources/sys/wde/wde-scrollbar.js

49 lines
2.0 KiB
JavaScript

class WdeScrollBar{
/**
* @param {HTMLElement} handler
* @param {HTMLElement} content
*/
constructor(handler, content){
let nonNativeScroll = false
handler.style.height = (content.clientHeight /content.scrollHeight)* handler.parentElement.clientHeight + 'px'
let max = handler.parentElement.clientHeight - handler.clientHeight
let yPosInit = 0
handler.addEventListener('mousedown', (event) => {
nonNativeScroll = true
yPosInit = event.clientY - Number(handler.style.top.replace('px','' ))
document.addEventListener('mousemove', drag);
document.addEventListener('mouseup', stop)
})
content.addEventListener('scroll', (event) =>{
if (!this.nonNativeScroll){
let handlerPathLength = handler.parentElement.clientHeight - handler.clientHeight //TODO recalculate only on resize event
let coefficient = (content.scrollHeight - content.clientHeight) /handlerPathLength
handler.style.top = content.scrollTop/coefficient + 'px'
}
})
function drag() {
// console.log(event.clientY - yPosInit, Number(handler.style.top.replace('px','' )))
let pos = event.clientY - yPosInit
let clampPos = Math.min(Math.max(pos, 0), max)
handler.style.top = clampPos + "px";
let handlerPathLength = handler.parentElement.clientHeight - handler.clientHeight //TODO recalculate only on resize event
let coefficient = (content.scrollHeight - content.clientHeight) /handlerPathLength
// console.log(clampPos, coefficient, content.clientHeight, clampPos* coefficient)
content.scrollTop = clampPos* coefficient
}
function stop() {
// console.log("stop")
document.removeEventListener('mousemove', drag);
document.removeEventListener('mouseup', stop)
nonNativeScroll = false
}
}
}