Home > Blockchain >  Image Scroller Jumping
Image Scroller Jumping

Time:10-09

I wonder if you could help.

I have the following code which uses the scroll-snap function in CSS to scroll through some images, but for some reason, when I drag the scroller, it jumps all over the place.

Apart from that, it seems to work great

Any suggestions on how this could be fixed?

Thanks

const childern = document.querySelectorAll(".childern");
const parent = document.querySelector(".horizontal-snap");

let startX;
let scrollLeft;
let isDown;

parent.addEventListener("mousedown", (e) => mouseIsDown(e));
parent.addEventListener("mouseup", (e) => mouseUp(e));
parent.addEventListener("mouseleave", (e) => mouseLeave(e));
parent.addEventListener("mousemove", (e) => mouseMove(e));

function mouseIsDown(e) {
  isDown = true;
  startX = e.pageX - parent.offsetLeft;
  scrollLeft = parent.scrollLeft;
}

function mouseUp(e) {
  isDown = false;
}

function mouseLeave(e) {
  isDown = false;
}

function mouseMove(e) {
  if (isDown) {
    e.preventDefault();
    //Move vertcally
    const x = e.pageX - parent.offsetLeft;
    const walkX = (x - startX) * 5;
    parent.scrollLeft = scrollLeft - walkX;
  }
}
.horizontal-snap {
  margin: 0 auto;
  display: grid;
  grid-auto-flow: column;
  gap: 1rem;
  height: calc(180px   1rem);
  padding: 1rem;
  max-width: 480px;
  overflow-y: auto;
  overscroll-behavior-x: contain;
  scroll-snap-type: x mandatory;
}

.horizontal-snap>a {
  scroll-snap-align: center;
}

.horizontal-snap img {
  width: 180px;
  max-width: none;
  object-fit: contain;
  border-radius: 1rem;
}
<div  style="scroll-behavior: smooth;">
  <a href="#" ><img src=""></a>
  <a href="#" ><img src=""></a>
  <a href="#" ><img src=""></a>
  <a href="#" ><img src=""></a>
  <a href="#" ><img src=""></a>
  <a href="#" ><img src=""></a>
</div>

CodePudding user response:

Just add e.preventDefault() to event dragstart. Like that.

parent.addEventListener("dragstart", (e) => e.preventDefault());
  • Related