Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 56 ยท Projects

Project: Image Gallery and Lightbox

Build a thumbnail gallery with delegated clicks and a fade-in lightbox that supports keyboard navigation, focus trapping, Escape to close and restored focus.

Almost every site with photos needs a gallery: a grid of small images, and a larger view when you click one. The larger view, called a lightbox, is a small dialog with its own rules. It must open and close smoothly, move between pictures, work with the keyboard, and never leave a keyboard or screen reader user lost behind it. Getting those details right is what separates a demo from a component you can ship.

In this project you will build the gallery in two steps. First the thumbnails and a delegated click that shows a larger preview. Then the real lightbox with a fade, previous and next buttons, arrow keys, Escape, a focus trap and focus restoration. The images all come from the sample illustration the course already hosts (/samples/sunset.svg), tinted with CSS filters so each thumbnail looks different. You can swap in your own image URLs without changing the logic.

What makes a good lightbox

Thumbnails Real buttons with meaningful alt text.
Fade Smooth open and close, no jump.
Keyboard Arrows move, Escape closes.
Focus Trapped inside, restored on close.
1 / 2

Build the thumbnails from data

Instead of writing six near-identical <img> tags, keep the photos in an array of small objects and generate the markup. Adding a seventh photo becomes a one-line change, and the click handler can use the index to know which object to show.

Each thumbnail is a real <button> containing the <img>, not a bare image with a click handler. A button is focusable, activates with Enter and Space, and is announced as a control, so you get keyboard and screen reader support for free. The accessible name of the button comes from the image's alt text, so write alt text that describes the picture, not "thumbnail 3".

The click handler uses delegation on the gallery container. It finds the closest .thumb, reads its data-index, and does not care how many thumbnails exist.

Step 1: thumbnails and a preview

Note how aria-current="true" marks the selected thumbnail for assistive technology, and the same attribute drives the visible border through CSS. One source of truth, no extra class to keep in sync.

The lightbox structure

The lightbox is an element with role="dialog", aria-modal="true" and a label. It contains the large image, a caption, a counter, and three buttons: previous, next and close. It starts hidden. We hide it with an inline display: none style, rather than the hidden attribute, so that .fadeIn() can reveal it.

A modal dialog makes three promises to its users:

  1. Focus moves in. When it opens, focus goes to a control inside (the Close button).
  2. Focus stays in. Tab and Shift+Tab cycle among the dialog's buttons and do not escape to the page behind. We also mark the page behind as inert, which removes it from the tab order and from the accessibility tree.
  3. Focus returns. When it closes, focus goes back to the thumbnail that opened it, so the person continues where they were.

Keyboard handlers are only active while the lightbox is open. We attach one keydown handler to the document with a namespace, keydown.lightbox, when opening and remove it with .off(".lightbox") when closing, so the gallery leaves nothing behind (see best practices).

Moving between pictures

The show(index) function is the heart of the component. It wraps the index with modulo arithmetic so Next on the last picture loops to the first, then updates the image, alt text, caption and counter. Every way of changing picture (the Next button, the Right arrow, a thumbnail click) calls it, so they can never disagree.

JavaScript
function show(index) {
  current = (index + photos.length) % photos.length;
  var photo = photos[current];
  $("#lb-img").attr("alt", altFor(photo)).css("filter", photo.filter);
  $("#lb-caption").text(photo.title);
  $("#lb-count").text((current + 1) + " / " + photos.length);
}

The + photos.length before the modulo matters. In JavaScript -1 % 6 is -1, not 5, so going backwards from the first picture would otherwise break.

Open a picture, press the arrow keys, Tab around, then press Escape. Try clicking the dark backdrop too: a click whose event.target is the backdrop itself (and not something inside the dialog) closes it.

Step 2: the full lightbox

Look closely at the lightbox element. Its stylesheet rule says display: flex (which centers the panel), while an inline style="display:none" keeps it hidden. .fadeIn() simply removes the inline none, so the stylesheet value takes over and the layout is correct from the first frame. Focus moves in the fade callback because an element that is still display: none cannot take focus.

Improving it further

  • Preload neighbors. In show(), create new Image() objects for current + 1 and current - 1 so the next picture appears instantly.
  • Touch gestures. Listen for touchstart and touchend on the panel and call show() for a horizontal swipe longer than about 50 pixels.
  • Prevent scroll behind. Set overflow: hidden on the body while the lightbox is open (in a real page, not this sandbox).
  • Respect motion preferences. Check window.matchMedia("(prefers-reduced-motion: reduce)").matches and set $.fx.off = true, which turns every jQuery animation into an instant change.
  • Real photos. Provide a small and a large URL per photo: thumbnails use the small file, and the lightbox loads the large one. Use width and height attributes on thumbnails to avoid layout jumps.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why are the thumbnails real <button> elements instead of images with click handlers?

    A native button gives keyboard operation and correct semantics for free. A clickable image would need tabindex, key handlers and a role added by hand.
  2. 2. What does (index + photos.length) % photos.length achieve in show()?

    In JavaScript the remainder of a negative number is negative, so adding the length first keeps the result between 0 and length minus 1.
  3. 3. Why is the keydown handler attached with the name keydown.lightbox only when the lightbox opens?

    Arrow keys should do nothing when the lightbox is closed. A namespace lets you remove only your handler without touching others on the document.
  4. 4. What are the three focus rules of a modal dialog implemented in this project?

    Moving focus into the dialog, trapping Tab inside it, and returning focus to the opener keeps keyboard and screen reader users oriented.
  5. 5. Why does the backdrop click handler check event.target === this?

    Clicks inside the panel bubble to the backdrop element, but then event.target is the inner element. Comparing it with the backdrop itself closes only for real backdrop clicks.

Summary

  • Generate thumbnails from an array of data; use real buttons with descriptive alt text, and delegate one click handler on the gallery.
  • aria-current marks the chosen item for assistive technology and for CSS at once.
  • A single show(index) function updates image, caption and counter, and wraps with (index + length) % length.
  • A modal lightbox moves focus in, traps Tab, marks the page inert, and returns focus to the opener on close.
  • Attach document-level key handlers with a namespace only while the dialog is open and remove them with .off(".lightbox").
  • Use $.fx.off to honor reduced-motion preferences, and preload neighbors for instant navigation.

Next: Project: Tabs and Accordion Components.