Skip to content
jshacks.dev
Browser

Build a lightbox for images

Open a full-size image in a lightbox using a native dialog, so you get the backdrop, Escape key and focus handling without a library.

1 min read
Summarize in AI

A lightbox is a modal with an image in it, which is exactly what <dialog> provides. You get the backdrop, the Escape key and inert background for free.

lightbox.htmlHTML
<dialog id="lightbox">
  <img alt="">
  <form method="dialog"><button>Close</button></form>
</dialog>
lightbox.jsJavaScript
const lightbox = document.querySelector('#lightbox');
const big = lightbox.querySelector('img');

document.addEventListener('click', (event) => {
  const thumb = event.target.closest('img[data-full]');
  if (thumb) {
    big.src = thumb.dataset.full;
    big.alt = thumb.alt;
    lightbox.showModal();
    return;
  }
  if (event.target === lightbox) lightbox.close();
});

Thumbnails carry the large file in data-full, so the page loads small images first. Clicking the dark area outside the picture hits the dialog element itself, because the backdrop counts as part of it, and the last line closes the dialog. The method="dialog" form closes it without any script, as the HTML Standard specifies.

Copy the thumbnail's alt into the large image so screen reader users hear what opened. Give the img a max-width: 100% in CSS so a large photo fits the viewport. If you need zoom or a gallery with many images, a library is a better fit.

Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Browser

Find the closest ancestor with closest

Walk up from an element to the nearest ancestor that matches a selector with closest, which includes the element itself. Works in all modern browsers.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.