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

49 lines
2.0 KiB
JavaScript
Raw Normal View History

2023-03-20 11:20:37 +00:00
class WdeScrollBar{
/**
* @param {HTMLElement} handler
2023-03-21 12:38:51 +00:00
* @param {HTMLElement} content
2023-03-20 11:20:37 +00:00
*/
2023-03-21 12:38:51 +00:00
constructor(handler, content){
let nonNativeScroll = false
handler.style.height = (content.clientHeight /content.scrollHeight)* handler.parentElement.clientHeight + 'px'
2023-03-20 11:20:37 +00:00
let max = handler.parentElement.clientHeight - handler.clientHeight
let yPosInit = 0
2023-03-21 12:38:51 +00:00
2023-03-20 11:20:37 +00:00
handler.addEventListener('mousedown', (event) => {
2023-03-21 12:38:51 +00:00
nonNativeScroll = true
2023-03-20 11:20:37 +00:00
yPosInit = event.clientY - Number(handler.style.top.replace('px','' ))
document.addEventListener('mousemove', drag);
document.addEventListener('mouseup', stop)
})
2023-03-21 12:38:51 +00:00
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'
}
})
2023-03-20 11:20:37 +00:00
2023-03-21 12:38:51 +00:00
function drag() {
// console.log(event.clientY - yPosInit, Number(handler.style.top.replace('px','' )))
2023-03-20 11:20:37 +00:00
let pos = event.clientY - yPosInit
let clampPos = Math.min(Math.max(pos, 0), max)
handler.style.top = clampPos + "px";
2023-03-21 12:38:51 +00:00
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)
2023-03-20 11:20:37 +00:00
2023-03-21 12:38:51 +00:00
content.scrollTop = clampPos* coefficient
2023-03-20 11:20:37 +00:00
}
function stop() {
2023-03-21 12:38:51 +00:00
// console.log("stop")
2023-03-20 11:20:37 +00:00
document.removeEventListener('mousemove', drag);
document.removeEventListener('mouseup', stop)
2023-03-21 12:38:51 +00:00
nonNativeScroll = false
2023-03-20 11:20:37 +00:00
}
}
}