Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
How do make a div scrollLeft based on clientX mousemove

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?

enter image description here

about 4 years ago ยท Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago ยท Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!