Skip to the page

Overlays and disclosure widgets · mid

Image carousel

A carousel keeps one index in state, wraps it safely with ((i % n) + n) % n, moves the track with a CSS transform, autoplays with an interval that is cleaned up and paused on hover, focus and hidden tabs, and gives every control a label.

The notes

What you must know

  • Index maths: next = (i + 1) % n; previous must handle −1: ((i − 1) % n + n) % n, because % keeps the sign in JavaScript.
  • Movement: transform: translateX(-index * 100%) with a CSS transition; not left/margin animations.
  • Autoplay: setInterval in an effect with cleanup; use the functional update setIndex(i => (i + 1) % n) to avoid a stale index; pause on hover and on focus within; pause when document.hidden; a visible Pause/Play button (first control per APG).
  • Controls: Previous/Next buttons with aria-labels; dots as buttons labelled 'Slide 3 of 5' with aria-current on the active one; arrow keys.
  • Swipe: pointer events (pointerdown/move/up) with a threshold; touch-action: pan-y.
  • Images: width/height or aspect-ratio to avoid layout shift; lazy-load slides beyond the neighbours.
  • prefers-reduced-motion: no autoplay and no slide animation.

The red pen

Common traps: mistake → fix

  • Mistake: setIndex(index + 1) inside an interval created once

    Fix: it is stuck on the first value (stale closure).

  • Mistake: i - 1 at index 0

    Fix: −1 and a blank slide.

  • Mistake: Autoplay that can't be paused

    Fix: accessibility failure.

  • Mistake: Interval never cleared

    Fix: multiple timers after re-renders; slides start racing.

Easy to hard

Questions interviewers ask, easy to hard

  1. Build a carousel with Previous, Next and dots.
  2. Add autoplay that pauses on hover.
  3. Add swipe on touch devices.
  4. Make it accessible.

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview