# gallery

A container of images shows one at a time and changes them with a displacement, a slide, a crossfade or a zoom.

The container shows one of its images, framed by that image’s own object-fit and object-position. A change runs a soft noisy wave across the picture that pushes the old one out and draws the new one in, slides the new one over the old, crossfades, or fades the new one in as it settles from a zoom. A whole index changes to its picture, a fraction from a tween holds the exact point between two, and clicks, swipes and the interval timer move the index too. Without WebGL the container is the layout you wrote, every image and alt text in place; keep captions and controls outside it, since its copy covers the whole box.

Module `media`, category Galleries and viewers. Import `@dioramajs/media/gallery`. [Source](https://github.com/MasterKurosava/diorama/blob/main/packages/media/src/gallery.ts)

Five hotel rooms in one box; a click on the picture or the Next button changes it with a soft, noisy wave.

```html title="index.html"
<div class="rooms" data-dio="gallery" style="touch-action: pan-y">
  <img src="/media/rooms/garden.avif" alt="The Garden Room: a double bed in white linen beside a tall window" width="1200" height="900" />
  <img src="/media/rooms/ocean.avif" alt="The Ocean Room: a king bed with a red throw, doors open to a balcony and the sea" width="1200" height="900" />
  <img src="/media/rooms/twin.avif" alt="The Twin Room: a garden window and a tea tray on a wooden stand" width="1200" height="900" />
  <img src="/media/rooms/glass.avif" alt="The Glass Room: a bed under steel-framed windows looking over dry hills" width="1200" height="900" />
  <img src="/media/rooms/studio.avif" alt="The Loft: a low bed against a brick wall and wide wooden floorboards" width="1200" height="900" />
</div>
```

## Usage

Put it on: a container of images, such as a scroll-snap strip.

`start()` registers `gallery`, so the attribute alone puts it on an element.

```html
<div class="shots" data-dio="gallery" data-dio-interval="5" style="touch-action: pan-y"><img src="/p/1.avif" alt="Front" /><img src="/p/2.avif" alt="Side" /><img src="/p/3.avif" alt="Detail" /></div>
```

In page transitions: Fades with the page transition; a keyed flight carries the current picture.

- Event `dio:index`, detail `{ index: number }`: A picture is reached, at the end of a change or when a tween stops on a whole index; index is its place among the pictures, from 0. Bubbles, for captions, dots and counters.

## Params

| Name | Attribute | Type | Default | Description |
| --- | --- | --- | --- | --- |
| `index` | `data-dio-index` | `number` 0 to 10 | `0` | Picture shown from 0, counting on past the last when it loops; a fraction holds a point between two. |
| `duration` | `data-dio-duration` | `number` 0.2 to 3 s | `1.1` | Length of a change. |
| `style` (rebuilds) | `data-dio-style` | `'displace' \| 'slide' \| 'fade' \| 'zoom'` | `'displace'` | displace pushes the pictures with a noisy wave; slide moves the new one in from the side, like a carousel; fade crossfades, for a calm page; zoom fades the new one in as it settles from a zoom, for a hero slideshow. |
| `strength` | `data-dio-strength` | `number` 0 to 1 | `0.25` | How far the displacement pushes the pictures. |
| `interval` | `data-dio-interval` | `number` 0 to 10 s | `0` | Time before the next picture, 0 for none; the timer pauses on hover and with focus inside. |
| `click` | `data-dio-click` | `boolean` | `true` | A click on the container shows the next picture. |
| `swipe` | `data-dio-swipe` | `boolean` | `true` | A horizontal swipe changes the picture; needs touch-action: pan-y on the container. |
| `loop` | `data-dio-loop` | `boolean` | `true` | After the last picture comes the first. Off, the ends hold: a click or swipe past them does nothing and the interval timer stops at the last. |
| `items` (rebuilds) | `data-dio-items` | `string` | `'img'` | Selector of the images inside the container. |
| `seed` (rebuilds) | `data-dio-seed` | `number` 1 to 100 | `1` | Shape of the displacement. |

Changing a param marked rebuilds re-runs the effect setup.

### Variants

- `style`: `displace`, `slide`, `fade`, `zoom`
  - `displace` pushes the pictures with a noisy wave.
  - `slide` moves the new one in from the side, like a carousel.
  - `fade` crossfades, for a calm page.
  - `zoom` fades the new one in as it settles from a zoom, for a hero slideshow.

## Inputs and frames

Reads [`motion`](/docs/api/inputs#motion), [`size`](/docs/api/inputs#size). Draws only while something on it moves, then stops. Only during a change; none at rest. The interval timer draws nothing while it waits, and it pauses under the pointer, with focus inside, off screen and in a background tab. See [how a frame is decided](/docs/concepts/frames).

## Reduced motion and touch

With reduced motion it shows a still frame: motion inputs are zero and time stands still. Every change is a short crossfade, and the interval timer does not advance.

Runs on every device. A tap shows the next picture. A swipe works when the container has touch-action: pan-y, so the page keeps vertical scrolling; without it the gesture belongs to the page.

```ts
import { start } from '@dioramajs/diorama'

start({ effects: { gallery: { reducedMotion: 'off' } } })
```

## Cost and quality

Loads 3.0 KB the first time a page uses it. GPU: Two or three texture reads per pixel, four during a displacement. Memory: Up to three pictures at a time, the current one and its neighbors, however long the gallery is.

See [the quality plugin](/docs/effects/quality).

## Recipes

### A product gallery with thumbnails

Set `style` to `slide` for the carousel move shoppers expect, and `loop` to false so the first and last views hold instead of wrapping around. The thumbnails sit under the box, not in it: the gallery’s copy covers the whole box, so anything inside would be hidden.

A lounge chair in five views that slide in from the side, chosen with a row of thumbnails.

```html title="index.html"
<div class="product">
  <div class="shots" data-dio="gallery" data-dio-style="slide" data-dio-loop="false" style="touch-action: pan-y">
    <img src="/media/chair/front.webp" alt="Lounge chair in moss velvet, from the front" width="960" height="640" />
    <img src="/media/chair/side.webp" alt="The chair in mustard velvet, from the side" width="960" height="640" />
    <img src="/media/chair/back.webp" alt="The chair in navy velvet, from behind" width="960" height="640" />
    <img src="/media/chair/tuft.webp" alt="The tufted back in rust velvet, close up" width="960" height="640" />
    <img src="/media/chair/leg.webp" alt="A walnut leg under teal velvet, close up" width="960" height="640" />
  </div>
  <div class="thumbs">
    <button type="button" data-show="0" aria-label="Front"><img src="/media/chair/front.webp" alt="" width="96" height="64" /></button>
    <button type="button" data-show="1" aria-label="Side"><img src="/media/chair/side.webp" alt="" width="96" height="64" /></button>
    <button type="button" data-show="2" aria-label="Back"><img src="/media/chair/back.webp" alt="" width="96" height="64" /></button>
    <button type="button" data-show="3" aria-label="Tufting"><img src="/media/chair/tuft.webp" alt="" width="96" height="64" /></button>
    <button type="button" data-show="4" aria-label="Leg"><img src="/media/chair/leg.webp" alt="" width="96" height="64" /></button>
  </div>
</div>
```

```ts title="script.ts"
import { pager } from '../_pager.ts'

// The thumbnails choose a view and show which one is on.
export default function mount(example: HTMLElement): () => void {
  const shots = example.querySelector<HTMLElement>('.product .shots')
  return shots ? pager(example, shots) : () => {}
}
```

Each thumbnail sets `index` on the instance, and the `dio:index` event marks the view on screen. The event also fires after a click or a swipe on the picture, so the row stays in step.

```ts
const shots = document.querySelector('.shots')
const thumbs = [...document.querySelectorAll('.thumbs button')]

thumbs.forEach((thumb, i) => {
  thumb.addEventListener('click', () =>
    app.effects.get(shots, 'gallery')?.set({ index: i }),
  )
})
shots.addEventListener('dio:index', (e) => {
  thumbs.forEach((thumb, i) =>
    thumb.setAttribute('aria-current', String(i === e.detail.index)),
  )
})
```

### A hero slideshow with a pause button

The `zoom` style fades each picture in as it settles from a slight zoom, a calm move for the first screen of a hotel or a restaurant. With `interval` set to 5 the pictures change every 5 seconds; the timer waits while the pointer is over the box or focus is inside it. Content that moves on its own for longer than 5 seconds needs a control that stops it (WCAG 2.2.2), so give the slideshow a pause button.

Four rooms of a house that change every 5 seconds, each settling from a slight zoom, with a pause button under them.

```html title="index.html"
<section class="house-hero" aria-label="The house">
  <div class="house" data-dio="gallery" data-dio-style="zoom" data-dio-interval="5" style="touch-action: pan-y">
    <img src="/media/house/terrace.avif" alt="The terrace: a table under a timber roof, the sea beyond the lawn" width="1200" height="515" />
    <img src="/media/house/drawing-room.avif" alt="The drawing room: sofas, a stone wall and tall windows onto the garden" width="1000" height="667" />
    <img src="/media/house/dining-room.avif" alt="The winter dining room: a long wooden table and benches on a tiled floor" width="1000" height="750" />
    <img src="/media/house/salon.avif" alt="The salon: white French windows under a fanlight" width="1000" height="667" />
  </div>
  <button type="button" class="house-pause" aria-pressed="false">Pause</button>
</section>
```

```ts title="script.ts"
import { app } from '../../../../docs/diorama.ts'

interface Gallery {
  set(values: { interval: number }): void
}

// The pause button turns the interval timer off and on again, as the recipe on the page shows.
export default function mount(example: HTMLElement): () => void {
  const house = example.querySelector('.house')
  const pause = example.querySelector<HTMLButtonElement>('.house-pause')
  if (!house || !pause) return () => {}
  const onClick = () => {
    const gallery = app.effects.get(
      house,
      'gallery' as never,
    ) as unknown as Gallery | undefined
    const paused = pause.getAttribute('aria-pressed') === 'true'
    gallery?.set({ interval: paused ? 5 : 0 })
    pause.setAttribute('aria-pressed', String(!paused))
  }
  pause.addEventListener('click', onClick)
  return () => pause.removeEventListener('click', onClick)
}
```

The button turns `interval` off and on again and keeps `aria-pressed` in step.

```ts
const house = document.querySelector('.house')
const pause = document.querySelector('.house-pause')

pause.addEventListener('click', () => {
  const paused = pause.getAttribute('aria-pressed') === 'true'
  app.effects.get(house, 'gallery')?.set({ interval: paused ? 5 : 0 })
  pause.setAttribute('aria-pressed', String(!paused))
})
```

### Name the picture on screen

Nothing in the page tells a screen reader that the picture changed. Put a caption with `aria-live="polite"` under the box and fill it from `dio:index`, whose `index` is the place of the picture reached, from 0. The example at the top of this page names the room and counts the pictures this way.

```html
<div
  class="rooms"
  data-dio="gallery"
  style="touch-action: pan-y"
>
  <img src="/media/rooms/garden.avif" />
  <img src="/media/rooms/ocean.avif" />
</div>
<p class="room-name" aria-live="polite">The Garden Room</p>
```

```ts
const rooms = document.querySelector('.rooms')
const name = document.querySelector('.room-name')
const pictures = [...rooms.querySelectorAll('img')]

rooms.addEventListener('dio:index', (e) => {
  name.textContent = pictures[e.detail.index].alt.split(':')[0]
})
```

### Scrub the pictures with the scroll

A fraction of `index` holds the exact point between two pictures, so a scrubbed tween plays each change at the pace of the scroll: the rooms of a house pass by as the reader moves down the page. Turn `click` and `swipe` off, so the scroll is the only thing that moves the pictures. [GSAP and Lenis](/docs/guides/gsap-lenis) covers tweens of params.

```ts
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'

gsap.registerPlugin(ScrollTrigger)

const rooms = app.attach('.rooms', 'gallery', {
  click: false,
  swipe: false,
})
gsap.to(rooms.params, {
  index: 4,
  ease: 'none',
  scrollTrigger: {
    trigger: '.rooms',
    start: 'top 70%',
    end: 'bottom 30%',
    scrub: true,
  },
})
```

## Notes

The copy covers the container’s whole box and frames each picture by that image’s own `object-fit` and `object-position`. Give every image the size of the box, as a scroll-snap strip with `flex: 0 0 100%` does, and keep captions, arrows and dots outside it. Without WebGL the strip is what visitors see and swipe.

The images stay in the page in their order, each with its alt text, so a screen reader can reach all of them. The gallery takes no keys and the box takes no focus: give keyboard users buttons that set `index`, as the recipes do.

`style`, `items` and `seed` rebuild the effect when they change. Set them in the markup rather than switching them while the gallery is on screen.

## Related

- [carousel](/docs/effects/carousel.md): Pictures on a 3D ring that turns with a drag, the keys, the page scroll or by itself, the front one enlarged.
- [coverflow](/docs/effects/coverflow.md): A row of covers as the classic cover flow: the middle one faces you, its neighbours turn away in perspective.
- [flipbook](/docs/effects/flipbook.md): The page images of a container become a book whose pages bend as they turn.
- [hover-preview](/docs/effects/hover-preview.md): Over a list of projects, the picture of the item under the pointer follows the pointer, stands beside the item or holds a fixed place.
- [lightbox](/docs/effects/lightbox.md): A click opens an image full screen: its copy flies out of the grid, pages and zooms.
- [polaroids](/docs/effects/polaroids.md): Photos scattered like prints on a table: drag one to the top, click it to hold it up large.
- [stack](/docs/effects/stack.md): The images of a container become a pile of cards; a swipe, a click or a key throws the top one off.
- [ambient](/docs/effects/ambient.md): A soft glow in the colors of the frame around a video or an image, like ambient mode.
- [GSAP and Lenis](/docs/guides/gsap-lenis.md)
- [Reduced motion](/docs/guides/reduced-motion.md)
