Search code examples
javascriptjqueryphotoswipe

PhotoSwipe: Is there a way to attach an event handler to the 'init' event or when the plugin opens the lightbox?


I'm using PhotoSwipe lightbox in conjuntion with Slick carousel for a project, and I want to have the carousel autoplay while the photoswipe lightbox is not open, but when the lightbox is opened, I want the autoplay to stop.

In the PhotoSwipe API they have a close and destroy event to listen for, but not an event for init or open. Has anyone found a good way to do this?

Something like:

$('#gallery').slick({
  autoplay: true,
  dots: true,
});

// ... Setup photoswipe...

pswp.listen('open', function() {
  $('#gallery').slickSetOption('autoplay', false, false);
});

pswp.listen('close', function() {
  $('#gallery').slickSetOption('autoplay', true, false);
});

pwsp.init();

Solution

  • So to do this, I found that you can just do what you need to do before init, then attach an event handler on close.

    Also there's an issue with Slick where the autoplay doesn't turn off using the slickSetOption command as of version 1.3.15.

    https://github.com/kenwheeler/slick/issues/731

    Here is my workaround for it based on one of the comments on the issue:

    // ... Setup PhotoSwipe ...
    slider.slickPause();
    slider.find('.slick-list').off('mouseleave.slick');
    
    gallery.listen('close', function() { 
      slider.slickPlay();
      slider.find('.slick-list').on('mouseleave.slick', function() {
        slider.slickPlay();
      });
    });
    
    gallery.init();