Skip to content
jshacks.dev
Browser

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.

1 min read
Summarize in AI

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.

carousel.cssCSS
.track {
  display: flex;
  overflow-x: auto;
  scroll-snap-type: x mandatory;
}
.track > img {
  flex: 0 0 100%;
  scroll-snap-align: start;
}
carousel.jsJavaScript
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}`);
});
Text
slide 2

Each 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.

Share

More snippets

APIs

Send JSON with fetch POST

Send a JSON body with fetch POST by stringifying the object and setting the Content-Type header, since fetch does not do either of those for you.

1 min read
APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.