Build an image carousel with scroll snap and JavaScript
Make a swipeable image carousel with CSS scroll snap and a few lines of JavaScript for the previous and next buttons, using scrollBy on the track.
A carousel is a horizontally scrolling box that stops at each slide. CSS scroll snap does the stopping, so JavaScript only needs to move the buttons.
.track {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
}
.track > img {
flex: 0 0 100%;
scroll-snap-align: start;
}const track = document.querySelector('.track');
document.querySelector('#next').addEventListener('click', () => {
track.scrollBy({ left: track.clientWidth, behavior: 'smooth' });
});
document.querySelector('#prev').addEventListener('click', () => {
track.scrollBy({ left: -track.clientWidth, behavior: 'smooth' });
});
track.addEventListener('scrollend', () => {
console.log(`slide ${Math.round(track.scrollLeft / track.clientWidth) + 1}`);
});slide 2Each slide is exactly one track wide, so scrolling by clientWidth lands on the next snap point. The scrollend event fires once the smooth scroll and the snap settle, which makes it a better place to update a dot indicator than scroll, which fires for every frame. See CSS Scroll Snap.
scrollend is in Chrome 114 and Firefox 109, and Safari support is recent, so check the compatibility table and debounce scroll where it is missing. Add alt text to every image and make the buttons real button elements.