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
javascript
javascript is an evil programming language. but apparently standard of industry, so like a terrible version of C, you has to know how it works.
- mouse drag scroll in js
- css class positioning
- clicking button to enlarge its parent in js
- getting parent of click in js
- change element style in js
- element style transition in css
- add class to element in js
- add and remove children to element in js
- duplicate element in js
- create element in js
- get children in js
- sleep in js
- getting element position in js
- getting element parent offset in js