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.
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.
<dialog id="lightbox">
<img alt="">
<form method="dialog"><button>Close</button></form>
</dialog>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.