Skip to content

Lightbox

A full-screen viewer for photos. Tap a thumbnail to open it; arrows, swipes and Esc work, and focus goes back to the photo that opened it.

CSS
css/components/lightbox.css
JS
js/components/lightbox.js

01 — Example

Gallery

Any container of a[data-lightbox-item] links. Each link points at the full image, so it still works without a script. data-caption is the first line; data-description adds a quieter second line.

02 — Behavior

Script

NameDetail
Keyboard← → move between photos, Esc closes. Focus returns to the thumbnail.
TouchSwipe to move, and the viewer clears the notch and home indicator.
FilteringPhotos that are hidden, or inside a hidden parent, are skipped, so it works with a filter.

03 — Usage

Use it for

  • Galleries and photo walls where people want to see each photo large.

Avoid

  • A single image that’s already large. Let it be.
  • Videos. Use the video figure.

04 — Accessibility

Notes

  • Every thumbnail needs real alt text.
  • The viewer is a native <dialog>; the caption is read when each photo opens.

05 — Without Jewel’s JS

What the script does

The script builds a full-screen <dialog>, fills it with the photo that was clicked and steps through the gallery. The CSS reads only the markup below, so a framework can render the viewer itself and leave out lightbox.js and data-component.

StateSet thisNotes
Viewer<dialog class="lightbox" aria-label="Photo viewer"> holding .lightbox__bar, figure.lightbox__figure and .lightbox__footerThe bar holds .lightbox__count and the close button. The footer holds the previous and next buttons around p.caption.lightbox__caption, which has aria-live="polite".
Opendialog.showModal()[open] lays it out, and CSS stops the page scrolling behind it.
Photosrc (the full image) and alt (the thumbnail’s) on img.lightbox__imgPreload the next and previous photos, as the script does.
CaptionText in .lightbox__caption, plus an optional <span class="lightbox__description">The description is a quieter second line.
Count“2 / 5” in .lightbox__count; hidden on the previous and next buttons when there’s one photoLeave out photos that are hidden, such as ones a filter hid.

Events and keyboard

  • Esc fires the dialog’s cancel event; the script calls preventDefault() and closes it itself. A click on the dialog, or on .lightbox__figure around the photo, closes it too.
  • ← → move between photos and wrap around. A swipe of more than 50px does the same.
  • On close, return focus to the thumbnail that opened it.
  • Let Cmd, Ctrl, Shift and Alt clicks on a thumbnail open the image link as usual.