Use (jquery.)photoswipe as lightbox etc. alternative with link fallback

Today I'd like to share a very simple trick which seems a bit underrepresentated in the documentation of jquery.photoswipe (built on Photoswipe): How to simply provide a photoswipe gallery function using the following class based markup:

  1. <div class="photoswipe-gallery">
  2.   <a href="path/to/large-image.png" title="title text">
  3.     <img src="path/to/thumbnail-image.png" alt="alt text">
  4.   </a>
  5.   <a href="path/to/large-image2.png" title="title text">
  6.     <img src="path/to/thumbnail-image2.png" alt="alt text">
  7.   </a>
  8. </div>

For more see https://github.com/yaquawa/jquery.photoswipe
There you can find the following description:

slideSelector

The selector of slides, the default selector is 'img'.

Make sure you include a img tag inside of the selected element, or you can just use a "bare img tag" just like the above sample markup.

If this selector indicates an a tag, the attribute href will be used as the "original image url" of that image.

If this selector indicates an a tag, and the value of the attribute href begin with the # that point to an element, the inner html of the pointed element will be shown.

And that's our simple trick! Just implement:

  1. $('.photoswipe-gallery').photoSwipe('a',
  2.   {
  3.     showHideOpacity: true,
  4.     getThumbBoundsFn: false
  5.   },
  6.   {
  7.     'gettingData':
  8.       function (index, item) {
  9.         // Get the size from the the large image.
  10.         // We don't want to provide data attributes manually so we recalculate the size
  11.         // on opening the large image here:
  12.         var self = this;
  13.         var img = new Image();
  14.         img.onload = function () {
  15.           item.w = this.width;
  16.           item.h = this.height;
  17.           self.updateSize(true);
  18.         };
  19.         img.src = item.src;
  20.       }
  21.   });

And that's it!

The helper function in "gettingData" is required to recalculate the size of the large image to display it larger than the thumbnail image. That saves us from manual data attributes.

This is very very simple, but helpful because the fallback works even if JavaScript fails and the large image will open on click. You don't need heavy implementations for this simple use-case anymore.

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.

More information about formatting options