ruby-on-railsphotoswipe

Photoswipe doesn't display some images in Rails app


I have a gallery of images, and by clicking on them, Photoswipe is opened. When I begin to list the images, some of them are not displayed, I can see only a black screen instead of an image. But when I reload the page, click the image - all of them are displayed in Photoswipe slider. Here is the code of my page:

<div class="row collapse full-width gallery-images" data-amount="<%= images.length %>">
  <% images.each_with_index do |image, index| %>
    <% if (index + 1) % 5 == 0 || (index + 2) % 5 == 0 %>
      <div class="large-6 columns">
        <%= link_to image_tag(image.file_name.url(:gallery),
                              alt: File.basename(image.file_name.url),
                              class: 'gallery-item'), '#' %>
      </div>
    <% else %>
      <div class="large-4 columns">
        <%= link_to image_tag(image.file_name.url(:gallery),
                              alt: File.basename(image.file_name.url),
                              class: 'gallery-item'), '#' %>
      </div>
    <% end %>
  <% end %>
</div>

<script>
  let galleryImages = $('.gallery-item');
  let galleryImagesArray = [];

  function collectArrayOfImages(image, array) {
    let imageSrc = image.attr('src');
    let img = new Image();
    img.src = imageSrc;
    array.push({
      src: imageSrc,
      w: img.width,
      h: img.height
    })
  }

  galleryImages.each(function () {
    collectArrayOfImages($(this), galleryImagesArray);
  });

  function photoswipeInit(e, i, array) {
    e.preventDefault();
    // init Photoswipe

    let pswpElement = document.querySelectorAll('.pswp')[0];

    // build items array
    let items = array;

    // define options (if needed)
    let options = {
      // optionName: 'option value'
      // for example:
      index: i, // start at first slide
      history: false
    };

    // Initializes and opens PhotoSwipe
    let gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
    gallery.init();
  }

  for(let i = 0; i < galleryImages.length + 1; i++) {
    galleryImages.eq(i).click(function (e) {
      photoswipeInit(e, i, galleryImagesArray);
    });
  }
</script>

Can it be turbolinks, if yes, how can I fix it? Any ideas what can it be? Thanks ahead.


Solution

  • I've found that in the array of images width and height were set to 0. So I had to put my function into a setTimeout:

    function collectArrayOfImages(image, array) {
        setTimeout(() => {
          let imageSrc = image.attr('src');
          let img = new Image();
          img.src = imageSrc;
          array.push({
            src: imageSrc,
            w: img.width,
            h: img.height
          });
        }, 1000);
      }
    

    It seems, that for some reason the function wasn't able to handle the process of filling the array.