Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda