Vanilla JavaScript Projects

Project 53, Website sections

Touch Image Slider

The photo slider almost every website needs, with real swipe support, autoplay that knows when to pause, and no heavy library.

Main API
Pointer events
Motion
CSS transform
Dependencies
None
Your browser
Checking

Swipe the slider

Drag or swipe the photo, use the arrows, dots or keyboard arrows. Autoplay pauses when you hover or focus.

How it works

  1. Move the whole trackAll slides sit in one row. Showing slide n just means moving the row by n times 100 percent.
  2. Follow the fingerPointer events work for touch, pen and mouse. While dragging, the track follows the finger with no transition.
  3. Decide on releaseIf the drag was more than 15 percent of the width, go to the next slide. Otherwise snap back.
slider.addEventListener("pointerdown", (e) => { startX = e.clientX; track.classList.add("drag"); });
slider.addEventListener("pointermove", (e) => {
  if (startX == null) return;
  dx = e.clientX - startX;
  track.style.transform = `translateX(calc(${-index * 100}% + ${dx}px))`;
});
slider.addEventListener("pointerup", () => {
  track.classList.remove("drag");
  go(Math.abs(dx) > width * 0.15 ? index + (dx < 0 ? 1 : -1) : index);
  startX = null;
});