John
John

Reputation: 4981

How to load Photoswipe with Ajax to get server side pictures?

I'm searching for a gallery library and I see PhotoSwipe. Actually I just made the tutorial in the documentation.

I don't see any tutorial to load my server side pictures dynamically.

I need to load them with Ajax because I have a datatables, and inside each row I set an icon. The user can click on this icon and it will appears a bootstrap modal. In this modal I have to show the thumbnails related with the clicked row. And when the user click on the thumbnails I need to show the gallery.

It's possible to load dynamically server side pictures ?

Upvotes: 2

Views: 1616

Answers (1)

vi5ion
vi5ion

Reputation: 1028

I think you can achieve this by initiating the gallery from the click event. If you make this a delegated event, it will also get triggered on newly created images. Then you only need to create the image array upon triggering the click event and fire up the gallery.

Your images should be added like this:

<img class="myAjaxLoadedImage" src="myAjaxLoadedImage1_thumbnail.jpg" alt="" 
     data-img-title="My title 1" data-img-src="myAjaxLoadedImage1.jpg" 
     data-img-width="800" data-img-height="600">

<img class="myAjaxLoadedImage" src="myAjaxLoadedImage2_thumbnail.jpg" alt="" 
     data-img-title="My title 2" data-img-src="myAjaxLoadedImage2.jpg" 
     data-img-width="400" data-img-height="700">
...

And the JS would then be:

(function($) {
  var pswp;

  $(function() {
    pswp = $('.pswp')[0];
    setGalleryClickEvents();
  });

  function setGalleryClickEvents() {
    $(document).on('click','.myAjaxLoadedImage',function(e) {
      if (pswp) {
        var options = {
          index: $(this).index()
          // + other PhotoSwipe options here...
        }
        var images = [];
        $('.myAjaxLoadedImage').each(function() {
          var $img = $(this);
          images.push({
            src: $img.data('imgSrc'),
            w: $img.data('imgWidth'),
            h: $img.data('imgHeight'),
            title: $img.data('imgTitle')
          });
        });
        var gallery = new PhotoSwipe(pswp, PhotoSwipeUI_Default, images, options);
        gallery.init();
      }
    });
  }
})(jQuery);

Upvotes: 2

Related Questions