dimsemenov / PhotoSwipe

JavaScript image gallery for mobile and desktop, modular, framework independent
http://photoswipe.com
MIT License
24.18k stars 3.31k forks source link

photoswipe opening wrong image after filter is applied #1517

Open codemare opened 6 years ago

codemare commented 6 years ago

After I apply a filter (setting some images to display none depending on class names). Photoswipe is opening according to the index number each image originally had. The array that photoswipe is pulling from is updated to only include filtered images. However, the index value that each image points to does not update.

If an image was item 5 in un-filtered gallery and number 1 in the filtered gallery, after applying filter, clicking on this image will open image number 5 in the filtered gallery.

This is my code that sets the array: ` getFigures = function() { var filteredFigures = []; $pic.find('figure:visible > a').map(function() { var $href = $(this).attr('href'), $size = $(this).data('size').toString().split('x'), $width = $size[0], $height = $size[1];

                var figures = {
                    src : $href,
                    w   : $width,
                    h   : $height
                };
                filteredFigures.push(figures);
            });
            return filteredFigures;
        };`

This is my code that is selecting index and opening photoswipe: ` $pic.on('click', 'figure', function(event) { event.preventDefault();

     filteredFigures = getFigures();
        $.map(filteredFigures, function(index, value) {
        image[index]     = new Image();
        image[index].src = value['src'];
    });
        var $index = $(this).index();
        var options = {
            index: $index,
            bgOpacity: 0.8,
            showHideOpacity: true
        }

        var lightBox = new PhotoSwipe($pswp, PhotoSwipeUI_Default, filteredFigures, options);
        lightBox.init();`

Thanks in advance for any help!

mdmatin4 commented 1 year ago

You're accessing the index before the images turn invisible. You've to get the index within the visible elements. I think the following will do the job.

`$pic.on('click', 'figure:visible', function(event) { event.preventDefault();

var filteredFigures = getFigures();

var $index = $(this).index('figure:visible');

$.each(filteredFigures, function(index, value) {
    value.index = index;
});

var options = {
    index: $index,
    bgOpacity: 0.8,
    showHideOpacity: true
};

var lightBox = new PhotoSwipe($pswp, PhotoSwipeUI_Default, filteredFigures, options);
lightBox.init();

}); `