Skip to content
jshacks.dev
Browser

Build an Image Carousel in Vanilla JavaScript

Build an image carousel in vanilla JavaScript with CSS scroll snap, previous and next buttons, dots, keyboard support, pausable autoplay and accessible labels.

7 min read
Summarize in AI
Flat illustration of shipping containers stacked on a ship, with the JavaScript, Google Chrome, GitHub Actions and Docker logos.

Carousels have a poor reputation, mostly because many are slow, inaccessible and automatic in ways that annoy people. A well-made one can still be the right tool for a gallery or a set of product photos. The good news is that modern CSS does most of the hard work. With scroll snapping the browser handles swiping, momentum and alignment natively, and JavaScript only adds buttons, indicators and a little state. This post builds an image carousel in vanilla JavaScript on top of scroll-snap-type: the markup, the CSS, previous and next buttons, dot indicators that follow the scroll position using IntersectionObserver, keyboard support, autoplay that stops when it should, and the ARIA attributes that make it usable with a screen reader. The scroll behavior is documented on MDN and the accessibility pattern in the WAI-ARIA carousel example.

Why scroll snap

A traditional carousel positions slides with transform: translateX() and handles touch events in JavaScript, which means writing swipe detection and momentum yourself. A scroll container with snapping gives you all of that: the track is an ordinary horizontally scrolling element, and the browser snaps to each slide when scrolling ends. Touch, trackpad, wheel and keyboard scrolling all work with no code, and the content remains reachable if JavaScript fails to load.

The markup

The carousel is a region with a label, a scrolling track of slides and controls.

index.htmlHTML
<section class="carousel" aria-roledescription="carousel" aria-label="Featured photos">
  <div class="track" id="track" tabindex="0">
    <figure class="slide" role="group" aria-roledescription="slide" aria-label="1 of 4">
      <img src="photos/lake.jpg" alt="A calm lake at sunrise" width="800" height="500">
      <figcaption>Lake at sunrise</figcaption>
    </figure>
    <figure class="slide" role="group" aria-roledescription="slide" aria-label="2 of 4">
      <img src="photos/forest.jpg" alt="Sunlight through tall pine trees" width="800" height="500" loading="lazy">
      <figcaption>Pine forest</figcaption>
    </figure>
    <figure class="slide" role="group" aria-roledescription="slide" aria-label="3 of 4">
      <img src="photos/desert.jpg" alt="Orange dunes under a clear sky" width="800" height="500" loading="lazy">
      <figcaption>Desert dunes</figcaption>
    </figure>
    <figure class="slide" role="group" aria-roledescription="slide" aria-label="4 of 4">
      <img src="photos/harbor.jpg" alt="Fishing boats in a small harbor" width="800" height="500" loading="lazy">
      <figcaption>Harbor</figcaption>
    </figure>
  </div>

  <div class="controls">
    <button type="button" id="prev" aria-label="Previous photo">‹</button>
    <div id="dots" role="group" aria-label="Choose a photo"></div>
    <button type="button" id="next" aria-label="Next photo">›</button>
    <button type="button" id="play" aria-pressed="false">Pause</button>
  </div>
</section>
<script type="module" src="carousel.js"></script>
Text
(a region with four photo slides, previous and next buttons, a dots area and a pause button)

Every image has a real alt, and width and height attributes so the layout does not jump as images load. The first slide loads eagerly, the others with loading="lazy". The aria-roledescription values tell assistive technology that this is a carousel of slides, and each slide's label says its position. The track has tabindex="0" so a keyboard user can focus the scrolling area and use the arrow keys, since a scrollable region must be reachable by keyboard.

The CSS

The track becomes a horizontal flex row that snaps, and each slide fills it.

carousel.cssCSS
.carousel { max-width: 800px; margin: 0 auto; }

.track {
  display: flex;
  overflow-x: auto;
  scroll-snap-type: x mandatory;
  scroll-behavior: smooth;
  scrollbar-width: none;
  overscroll-behavior-x: contain;
}

.track::-webkit-scrollbar { display: none; }

.slide {
  flex: 0 0 100%;
  margin: 0;
  scroll-snap-align: center;
  scroll-snap-stop: always;
}

.slide img { display: block; width: 100%; height: auto; }

.controls { display: flex; gap: 0.75rem; align-items: center; justify-content: center; padding: 0.5rem; }

#dots button { width: 0.75rem; height: 0.75rem; border-radius: 50%; border: 1px solid currentColor; background: transparent; padding: 0; }
#dots button[aria-current="true"] { background: currentColor; }

@media (prefers-reduced-motion: reduce) {
  .track { scroll-behavior: auto; }
}
Text
(slides sit side by side, the track scrolls horizontally and snaps to one slide at a time)

scroll-snap-stop: always stops a fast swipe from skipping several slides. overscroll-behavior-x: contain prevents a swipe at the end from triggering the browser's back gesture. The prefers-reduced-motion rule makes programmatic scrolling instant for people who ask for less animation.

Buttons and navigation

Moving to a slide means scrolling the track to that slide's position. scrollIntoView is tempting, but it also scrolls the page vertically, so scroll the track directly.

carousel.jsJavaScript
const track = document.querySelector("#track");
const slides = [...track.querySelectorAll(".slide")];
const prev = document.querySelector("#prev");
const next = document.querySelector("#next");
let current = 0;

function goTo(index) {
  const target = Math.max(0, Math.min(index, slides.length - 1));
  track.scrollTo({ left: slides[target].offsetLeft - track.offsetLeft, behavior: "smooth" });
}

prev.addEventListener("click", () => goTo(current - 1));
next.addEventListener("click", () => goTo(current + 1));

goTo(0);
console.log(slides.length);
Text
4

The Math.max and Math.min clamp the index so the buttons cannot go out of range. The offset is measured relative to the track, since offsetLeft is relative to the nearest positioned ancestor. Mark the track's parent as position: relative if the numbers look off.

Track the current slide with IntersectionObserver

Listening to the scroll event to find the current slide is wasteful. An IntersectionObserver tells you when a slide is mostly visible, and it runs off the scroll hot path.

observer.jsJavaScript
const dotsEl = document.querySelector("#dots");

slides.forEach((slide, index) => {
  const dot = document.createElement("button");
  dot.type = "button";
  dot.setAttribute("aria-label", `Show photo ${index + 1}`);
  dot.addEventListener("click", () => goTo(index));
  dotsEl.append(dot);
});

const dots = [...dotsEl.children];

function setCurrent(index) {
  current = index;
  dots.forEach((dot, i) => dot.setAttribute("aria-current", String(i === index)));
  prev.disabled = index === 0;
  next.disabled = index === slides.length - 1;
}

const observer = new IntersectionObserver(
  (entries) => {
    for (const entry of entries) {
      if (entry.isIntersecting) setCurrent(slides.indexOf(entry.target));
    }
  },
  { root: track, threshold: 0.6 }
);

slides.forEach((slide) => observer.observe(slide));
setCurrent(0);
console.log(dots.length, prev.disabled);
Text
4 true

A threshold of 0.6 means a slide counts as current when 60 percent of it is visible, which avoids two slides both reporting during a swipe. The dots are real buttons, not clickable divs, so they work with the keyboard, and the current one carries aria-current. Disabling the previous button on the first slide stops dead clicks; if you prefer looping, wrap the index instead.

Keyboard support

The focusable track already scrolls horizontally with the left and right arrow keys in browsers, and snapping aligns the result. Add Home and End for convenience.

keyboard.jsJavaScript
track.addEventListener("keydown", (event) => {
  if (event.key === "Home") { event.preventDefault(); goTo(0); }
  if (event.key === "End") { event.preventDefault(); goTo(slides.length - 1); }
});
Text
(Home jumps to the first photo and End jumps to the last)

Autoplay, carefully

Automatic rotation is the most abused carousel feature. If you include it, follow three rules: it must start only if the user has not asked for reduced motion, it must stop when the user interacts or when the carousel has focus or the pointer is over it, and there must be a visible pause control. WCAG requires a mechanism to pause moving content that lasts more than five seconds.

autoplay.jsJavaScript
const playButton = document.querySelector("#play");
const reduced = window.matchMedia("(prefers-reduced-motion: reduce)");
let timer = null;
let userPaused = reduced.matches;

function start() {
  stop();
  if (userPaused) return;
  timer = setInterval(() => goTo(current === slides.length - 1 ? 0 : current + 1), 5000);
}

function stop() {
  clearInterval(timer);
  timer = null;
}

function setPaused(value) {
  userPaused = value;
  playButton.setAttribute("aria-pressed", String(value));
  playButton.textContent = value ? "Play" : "Pause";
  if (value) stop(); else start();
}

playButton.addEventListener("click", () => setPaused(!userPaused));
track.addEventListener("pointerenter", stop);
track.addEventListener("pointerleave", start);
track.addEventListener("focusin", stop);
track.addEventListener("focusout", start);
document.addEventListener("visibilitychange", () => (document.hidden ? stop() : start()));

setPaused(userPaused);
console.log(playButton.textContent);
Text
Pause

The printed text assumes the user has not requested reduced motion; with that preference on, the app starts paused and the button reads "Play". The pause on visibilitychange saves work in background tabs. Set aria-live="off" on the track while it rotates, and polite when it is paused, so a screen reader is not interrupted every five seconds.

Practical notes

Images are the weight of a carousel, so give the first slide fetchpriority="high" if it is the largest content on the page, lazy-load the rest and serve sizes that match the display. Test on a real phone: swiping should feel native because it is native scrolling. Check that the layout holds when the window is resized, since flex: 0 0 100% adapts automatically, and test with JavaScript disabled, where the track is still a scrollable row of photos. If you only have one image, do not render controls at all. If your slides contain links or forms, remember that off-screen slides are still in the tab order, so mark hidden ones inert if that becomes a problem.

Check the carousel the way a visitor would. Swipe on a phone, scroll with a trackpad, press the arrow buttons and click the dots, and confirm that the dot and the disabled state of the buttons follow the slide in every case. Resize the window while a middle slide is showing: with snapping, the browser keeps the slide aligned, but if the layout shifts you may need to call goTo(current) from a resize listener, which is a safe fix because goTo clamps the index.

Test with the keyboard alone, using Tab to reach the track and the arrow, Home and End keys to move, and confirm the focus outline is visible on the track. Turn on a screen reader and check that the region is announced as a carousel, each slide announces its position and the dots have meaningful names. Throttle the network in the developer tools to watch lazy images load, and make sure no slide changes size when its image arrives. Finally, turn on the reduced motion setting and confirm that autoplay starts paused and scrolling is instant.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

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