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

54 lines
2.3 KiB
JavaScript
Raw Normal View History

2023-03-20 11:20:37 +00:00
class WdeScrollBar{
/**
2023-03-22 21:53:06 +00:00
* @param {HTMLElement} scrollBarContainer
2023-03-21 12:38:51 +00:00
* @param {HTMLElement} content
2023-03-20 11:20:37 +00:00
*/
2023-03-22 21:53:06 +00:00
constructor(scrollBarContainer, content){
2023-03-21 12:38:51 +00:00
let nonNativeScroll = false
2023-05-07 19:56:40 +00:00
// console.log(scrollBarContainer, content)
// let handler = scrollBarContainer.children[0]
//TODO On scroll move focus on window?
let handler = scrollBarContainer.querySelector(".ScrollBarScrollElement") //TODO Refactor classes
// console.log(handler)
2023-03-21 12:38:51 +00:00
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
}
}
}