Build an Image Carousel

Track an index in JavaScript, mutate transform: translateX in CSS. Build a smooth slide carousel with prev/next buttons.

Step 1 of 2

The carousel pattern: index + transform

Carousels look complex but the core is simple:

  1. Stack all the slides in a row inside a wrapper. Each slide is the same width.
  2. Use overflow: hidden on the parent so only one slide is visible at a time.
  3. Track an integer index in JavaScript.
  4. On 'next', increment the index. On 'prev', decrement. (Clamp or wrap as needed.)
  5. Set style.transform = 'translateX(-' + (index * 100) + '%)' on the row of slides.

CSS transitions do the smooth animation; JavaScript only changes the number.

Think of it this way: Picture a film reel pulled across a projector. The frames are all in a long strip; only the one currently in front of the lens is visible. Pulling the strip is the transform.
Learn more on MDN