mouse drag scroll in js

Table of Contents

stackoverflow question Solution: Add mouse event listener to the parent div, i.e. the view port

let mouseDown = false;
let startX, scrollLeft;
const slider = document.querySelector('.parent');

const startDragging = (e) => {
  mouseDown = true;
  startX = e.pageX - slider.offsetLeft;
  scrollLeft = slider.scrollLeft;
}

const stopDragging = (e) => {
  mouseDown = false;
}

const move = (e) => {
  e.preventDefault();
  if(!mouseDown) { return; }
  const x = e.pageX - slider.offsetLeft;
  const scroll = x - startX;
  slider.scrollLeft = scrollLeft - scroll;
}

// Add the event listeners
slider.addEventListener('mousemove', move, false);
slider.addEventListener('mousedown', startDragging, false);
slider.addEventListener('mouseup', stopDragging, false);
slider.addEventListener('mouseleave', stopDragging, false);
.parent{
  width:300px;
  border:5px solid red;
  overflow-x: hidden;
  float:left;
}
.child{
  width:1000px;
  float:left;
  font-size:15px;
  font-family:arial;
  padding:10px;
  cursor: pointer;
}
<div class="parent">
    <div class="child">
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum
    </div>
</div>

Backlinks

Author: Linfeng He

Created: 2024-04-03 Wed 23:21