I have a scrollable div that I want to scroll when dragging the mouse inside of it.
I have a very basic implementation in this code pen.
I can't however understand how to think of scrollLeft and clientX? I think I need ๐ตโ๐ซ to set the scrollLeft position to the clientX + the position of the scrollBar once the drag staretd. But they are somehow on different relative positions?
Resulting in a bit of "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 image I've just clicked at the start of the bar but the scrollLeft is at 548 and the clientX is at 282?
How can I make this a bit smoother?
You should reset the initPosition every time the mouse moves and is dragging, and instead of reassigning the scrollLeft, you can subtract from it the difference between the clientX and the initPosition:
var dragging = false;
var startX = 0;
var elem = document.querySelector('.draggable');
document.addEventListener('mousedown', (e) => (dragging = true,startX = e.clientX))
document.addEventListener('mouseup', () => (dragging = false))
document.addEventListener('mousemove', function(e) {
if (!dragging) return;
elem.scrollLeft -= e.clientX - startX;
startX = e.clientX;
})
.draggable {
overflow-y: auto;
}
.draggable .content {
width: 200%;
background-color: red;
height: 100px;
}
<div class="draggable">
<div class="content"></div>
</div>