I am attempting to create a scrollable div that scrolls when the mouse is dragged inside of it.
For a basic implementation, check out this code pen.
I am struggling with understanding how to work with scrollLeft
and clientX
. I believe I need to adjust the scrollLeft
position to be
clientX + the initial scrollBar position when the drag begins
. However, they seem to be in different relative positions?
This leads to a slightly "jumpy" feeling when starting to drag.
function mouseMove(event) {
if (!dragging) return;
const {scrollLeft} = initScroll;
// Even if I click exactly where the bar starts the positions are way off ...
div.scrollLeft = event.clientX + scrollLeft;
}
In this screenshot, I clicked at the beginning of the bar but the scrollLeft value is 548 while clientX is 282?
How can I improve the smoothness of this interaction?