Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138221

Add easing/smooth scroll to click and drag with js

$
0
0

I found a simple Codepen which allows me to drag and scroll a gallery with images. It is working fine, but I need a way to add "smooth grabbing/scrolling" to this function. Basically I want to emulate the scroll for example on an iPhone.

Can someone please help me out. I am a total beginner in Javascript. Here is the link to the code: Horizontal Click and Drag Scrolling with JS

const slider = document.querySelector('.items');
let isDown = false;
let startX;
let scrollLeft;

slider.addEventListener('mousedown', (e) => {
  isDown = true;
  slider.classList.add('active');
  startX = e.pageX - slider.offsetLeft;
  scrollLeft = slider.scrollLeft;
});
slider.addEventListener('mouseleave', () => {
  isDown = false;
  slider.classList.remove('active');
});
slider.addEventListener('mouseup', () => {
  isDown = false;
  slider.classList.remove('active');
});
slider.addEventListener('mousemove', (e) => {
  if(!isDown) return;
  e.preventDefault();
  const x = e.pageX - slider.offsetLeft;
  const walk = (x - startX) * 3; //scroll-fast
  slider.scrollLeft = scrollLeft - walk;
  console.log(walk);
});

Thanks in advance.


Viewing all articles
Browse latest Browse all 138221

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>