Search code examples
ajaxfancybox

Fancybox thumbnail on AJAX


I am using fancybox gallery, that I am loading dynamically. I have always one picture with data-fancybox attribute and with ID.

JS is like this:

  $('[data-fancybox]').each(function(e){
  var idgal = $(this).data("fancybox");
  $(this).fancybox({
    loop: false,
    onInit: function (instance) {
        $.ajax({
            type: 'POST',
            url: '/loadGallery.php?gallery='+idgal,
            dataType: 'json',
            success: function (data) {
              $.each(data, function (index,src) {
                instance.addContent({
                  'type': 'image',
                  'src': src.src
                });
              });
            }
        });
    },
    thumbs: {
        autoStart: true,
        axis      : 'x'
    }
  })
})

Problem is, that I don't get thumbnails of dynamically loaded images. Any ideas? Thanks!


Solution

  • If you ask for the last fancyBox (v 3.5.7), to get thumbnails you also need to proceed thumbnails URL (inside options/opts key). And, most important, at the end, need to reinitialize thumbs (eg. after each loop inside Ajax success block).

    Here is only part from your example with changes:

        // Ajax success
        success: function ( data ) {
    
          $.each(data, function (index, src) {
            instance.addContent({
              'type': 'image',
              'src': src.src,
              'opts': {         
                   'thumb': 'thumb.jpg' // thumbnail url (eg. src.opts.thumb)
              }
            });
          });
    
          // reinitialize Thumbs
          instance.Thumbs.init(instance);
    
          // optional: to get thumbs autoStart
          instance.Thumbs.show();          
    
        } // success