Skip to content
Tutorials Center
My learning

Topics

Lesson 139 of 156 ยท Projects

Project: Lightbox and Gallery Filter

Build a filterable image gallery and an accessible lightbox with the dialog element, previous/next navigation, keyboard support and wrap-around arithmetic.

Click a thumbnail, the picture grows to fill the screen over a dimmed page, you flick through the rest with the arrow keys, and Escape takes you back. That is a lightbox, and it is one of the most copied widgets on the web. Add a row of filter buttons ("All", "Nature", "City") above the thumbnails and you have a complete portfolio gallery.

In this project you will build both parts and connect them so the lightbox only walks through the pictures that the current filter shows. You will use the built-in <dialog> element, which gives you a dimmed backdrop, a focus trap and the Escape key for free, so you only write the parts that are truly yours: the data, the filtering, and the wrap-around navigation.

It builds on Creating and Removing Elements, Bubbling, Capturing and Delegation, Events and Array Methods.

Plan: data first, pixels second

Galleries are lists, so describe them as data. Each picture is an object with a title, a category and a colour. To keep this lesson self-contained we draw the "photos" ourselves as small SVG images generated in JavaScript and turned into data: URLs. In your own project, each object would have a real src, a thumbnail thumb URL and descriptive alt text.

The whole interface can then be driven by two pieces of state:

  • filter: the active category ("all" by default).
  • current: the index of the picture shown in the lightbox, within the filtered list.

Everything on screen is a function of those two values.

Step 1: Filtering and wrap-around navigation

Two small pure functions carry the gallery's logic:

  1. visibleItems(items, filter) returns the pictures to show.
  2. step(index, delta, length) moves forward or backward and wraps: after the last picture comes the first, and before the first comes the last.

Wrap-around needs one careful line. In JavaScript the % operator keeps the sign of the left operand, so -1 % 5 is -1, not 4. The fix is to add the length before taking the remainder: (index + delta + length) % length.

JS Step 1: Gallery logic

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that step() also handles bigger jumps, and a length of 1 simply stays on the same picture. We will keep a guard for an empty list in the interface code, because % 0 gives NaN.

Step 2: The filterable grid

Now draw the grid. Build every thumbnail once from the data and, when a filter button is pressed, hide or show the existing elements. Re-creating the whole grid on every click would work too, but toggling the hidden property keeps the images loaded (nothing flickers, and nothing is downloaded twice).

Details that matter:

  • The thumbnails are buttons, not bare images with click handlers. Buttons are focusable and respond to Enter and Space with no extra code.
  • Filter buttons use aria-pressed so assistive technology knows which one is on.
  • The live region (role="status") says "3 pictures shown", because hiding items visually is otherwise silent for screen reader users.
  • One listener on the filter bar and one on the grid (event delegation), no matter how many items there are.
Step 2: Filterable gallery grid

Press Nature, then City, then All. Because every thumbnail already exists, switching is instant. The key idea is render(): it reads the two state values and makes the screen match, and it is safe to call as often as you like. Notice button.hidden = !match: the hidden property is a boolean, so there is no if/else. We added .grid [hidden] { display: none; } because display: grid or display: block on an element would otherwise override the browser's default hidden style.

Step 3: The lightbox

Now add the big view. A <dialog> opened with showModal() does the heavy lifting:

  • It is shown in the top layer, above everything, with a ::backdrop you can style.
  • Everything outside it becomes inert, so keyboard focus can't escape behind the overlay.
  • Escape closes it, and focus returns to the button that opened it.

What the dialog does not do is know about your pictures, so we add:

  • A shownList array: the pictures that match the current filter, in order. The lightbox moves through this list.
  • open(index), close() and go(delta) functions. go() uses step() from the first step.
  • Previous and next buttons, arrow-key support, and a counter like "3 / 6".
  • Backdrop click closes the dialog. A click on the backdrop reports the <dialog> itself as its target (the content sits inside a wrapper), which is how we tell the two apart.
Step 3: Gallery with lightbox

Open any picture and try everything: the arrow buttons, the left and right arrow keys, Tab (focus stays inside the viewer), Escape, and a click on the dark backdrop. Then close it, press City, and open a picture again: the counter now reads "x / 3", because shownList only contains the city pictures. That is the payoff of keeping the filtered list as state instead of reading the DOM.

Here is why the code is arranged the way it is:

  • open() looks the picture up by its id, not its position in the grid. When a filter is active, grid position and list position differ, and ids never lie.
  • event.target === box detects backdrop clicks. The <dialog> is padded with nothing and its content lives inside .frame, so a click on the dark area has the dialog itself as its target, while a click on the picture has the image or a button.
  • Focus management is free. showModal() moves focus into the dialog and restores it to the thumbnail on close. If you built the overlay out of a plain <div>, you would have to write the focus trap, the Escape key and the inert handling yourself. That is a lot of fiddly work to get right.
  • go() guards the empty list so step() never divides by zero.

For large images, preload the neighbours: after showing picture n, create new Image() objects for n - 1 and n + 1 and set their src. By the time the person clicks next, the file is already in the cache.

Ideas to extend it

  • Swipe on touch screens. Compare pointerdown and pointerup x-positions and call go(-1) or go(1) when the difference passes a threshold (about 50 px).
  • Deep links. Put the current id in location.hash and open the lightbox from it on load, so a visitor can share the link to one picture.
  • Zoom. Toggle a class on the big image that sets transform: scale(2) and follows the pointer with transform-origin.
  • Search and filter together. Add a text box and extend render() to match titles as well as categories.
  • Real images. Use srcset and a small thumb URL for the grid, so the full-size file loads only when opened.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does -1 % 5 evaluate to in JavaScript?

    % is a remainder operator and keeps the sign of the left operand, so the result is -1. That is why wrap-around code adds the length first: ((i + delta) % length + length) % length.
  2. 2. Why does the lightbox walk through shownList and not the grid's DOM order?

    shownList is the filtered data. Navigating it means Next never lands on a picture the visitor filtered out, and the counter always matches what they can see.
  3. 3. What do you get for free by opening the viewer with dialog.showModal()?

    A modal dialog is rendered in the top layer, makes the rest of the page inert and handles Escape. Next/previous logic is still yours to write.
  4. 4. How does the code tell a click on the backdrop from a click on the picture?

    Content lives inside an inner frame, so clicks on it report a child element as the target. A click outside it, on the ::backdrop, reports the <dialog> itself.
  5. 5. Why are the thumbnails <button> elements and not clickable <img> tags?

    A bare <img> isn't focusable, so keyboard users couldn't open it. A <button> wrapping the image gets focus, Enter and Space behavior, and an accessible name from the image's alt.

Summary

  • Describe the gallery as data (items) plus two state values (filter, current), and write a render() that makes the screen match them.
  • Build thumbnails once and toggle hidden; add [hidden] { display: none } when your CSS sets display.
  • Wrap-around navigation needs ((i + delta) % n + n) % n, because % can return negative numbers.
  • <dialog> with showModal() gives you a backdrop, focus trapping, Escape and focus restoration; you still write navigation, the counter and backdrop clicks.
  • Use <button> for clickable thumbnails, aria-pressed for filter buttons and a role="status" line to announce results.
  • Navigate the filtered list, find pictures by id, and preload neighbouring images for a smooth feel.

Next: Project: Digital and Analog Clock, Stopwatch.