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:
- Stack all the slides in a row inside a wrapper. Each slide is the same width.
- Use
overflow: hiddenon the parent so only one slide is visible at a time. - Track an integer
indexin JavaScript. - On 'next', increment the index. On 'prev', decrement. (Clamp or wrap as needed.)
- 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