Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda