PhotoSwipe does not support captions natively. You can implement a basic caption by using the uiRegister event to register a custom UI element. This element can be dynamically updated during the change event to pull text from a hidden element (e.g., .hidden-caption-content) or from the image's alt attribute.
Accessibility Note: Ensure captions are accessible to screen reader users outside of the lightbox (e.g., using alt attributes, aria-labelledby, or <figcaption> inside a <figure>), as the lightbox may be disabled in unsupported browsers.
import PhotoSwipeLightbox from '/photoswipe/photoswipe-lightbox.esm.js';
const options = {
gallery:'#gallery--with-custom-caption',
children:'.pswp-gallery__item',
pswpModule: () => import('/photoswipe/photoswipe.esm.js')
};
const lightbox = new PhotoSwipeLightbox(options);
lightbox.on('uiRegister', function() {
lightbox.pswp.ui.registerElement({
name: 'custom-caption',
order: 9,
isButton: false,
appendTo: 'root',
html: 'Caption text',
onInit: (el, pswp) => {
lightbox.pswp.on('change', () => {
const currSlideElement = lightbox.pswp.currSlide.data.element;
let captionHTML = '';
if (currSlideElement) {
const hiddenCaption = currSlideElement.querySelector('.hidden-caption-content');
if (hiddenCaption) {
// get caption from element with class hidden-caption-content
captionHTML = hiddenCaption.innerHTML;
} else {
// get caption from alt attribute
captionHTML = currSlideElement.querySelector('img').getAttribute('alt');
}
}
el.innerHTML = captionHTML || '';
});
}
});
});
lightbox.init();