dimsemenov / photoswipe-dynamic-caption-plugin

A dynamic caption plugin for PhotoSwipe v5. Automatically positions the caption aside or below the image.
MIT License
70 stars 12 forks source link

Adding a button that triggers a function onClick in Caption (pswp-caption-content) #19

Open MATTiVOLTARii opened 1 year ago

MATTiVOLTARii commented 1 year ago

Nice Work with PhotoSwipe! I want to include a button in the caption that executes a function when clicked. Unfortunately, the "onClick" is not being executed.

<div className="pswp-caption-content">                    
                    <button onClick={() => handlerClick()}>Click</button>                      
                      <div>
                        <Text size="xl" weight={700}>
                          Lorem ipsum dolor (1933)
                        </Text>
                      </div>
                      Color photograph 12 x 10
                    </div>

Does anyone have an idea of how it could work?

dimsemenov commented 1 year ago

The plugin doesn't do anything special when adding the content, it's just simple innerHTML https://github.com/dimsemenov/photoswipe-dynamic-caption-plugin/blob/main/photoswipe-dynamic-caption-plugin.esm.js#L247

You may try using dynamicCaptionUpdateHTML event:

const lightbox = new PhotoSwipeLightbox({
  gallerySelector: '#gallery',
  childSelector: '',
});

const captionPlugin = new PhotoSwipeDynamicCaption(lightbox, {
  type: 'auto',
});

lightbox.on('dynamicCaptionUpdateHTML', (e) => {
  console.log(e.captionElement, e.slide);
});

lightbox.init();
MATTiVOLTARii commented 1 year ago

Oh, I see! Thanks! Now I understand. The elements are reset through innerHTML and are no longer connected to the original DOM, which is why my JSX onClick directive is no longer handled. Is there a workaround for that? So that the button works as it is without having to reset it through lightbox.on, or is it possible to reference this button?

ikabod commented 1 year ago

You can give your button an id and handle all click events of the document / body.

In the event handler function check if the button was clicked and call the desired function.