Skip to content

Instantly share code, notes, and snippets.

@thesan
Created May 26, 2015 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thesan/342108caa8431549a8e3 to your computer and use it in GitHub Desktop.
Save thesan/342108caa8431549a8e3 to your computer and use it in GitHub Desktop.
jQuery integration of PhotoSwipe (https://github.com/dimsemenov/photoswipe)
/*
* jQuery integration of PhotoSwipe (https://github.com/dimsemenov/photoswipe)
* Usage:
*<div id="gallery">
* <a data-src="path/to/image1" data-w="1024" data-h="800"><img src="path/to/thumbnail1"/></a>
* ...
*</div>
*<script type="text/javascript">
* var pswp;
* $( function() { pswp = $("#gallery").photoswipe() ) );
*</script>
*<script type="text/javascript" src="path/to/photoswipe.js>
*/
(function ( $ ) {
Photoswipe = {
pswpElement: [],
slides: [],
options: {},
gallery: undefined, // Contain the photoswipe gallery object.
initialize: function(container) {
/*
* Set every parameters necessary to initialize the gallery,
* as attribute of this object.
*/
this.pswpElement = $('.pswp').get(0);
var thumbs = container.children();
this.slides = thumbs.map( this._getSlideInfo );
this.options.getThumbBoundsFn = this._getThumbBoundsFn(container);
thumbs.click( this._onThumbClicked.bind(this) ); // !!! include a Function.prototype.bind() polyfill for IEs < 9
return this;
},
_onThumbClicked: function(e) {
/*
* Each time a thumbnail is clicked reinitialize the gallery,
* with the index of the slide to start at.
* update the gallery attribute.
*/
var options = this.options;
options.index = $(e.currentTarget).index();
this.gallery = new PhotoSwipe( this.pswpElement, PhotoSwipeUI_Default, this.slides, options );
this.gallery.init();
},
_getSlideInfo: function(index, thumb) {
/* For each slide return necessary information to start the gallery. */
return {
src: thumb.getAttribute("data-src"),
w: thumb.getAttribute("data-w"),
h: thumb.getAttribute("data-h"),
};
},
_getThumbBoundsFn: function(container) {
return function(index) {
/*
* Used for the zoom in/out animation,
* has to select the right thumb based on "index"
* See Options -> getThumbBoundsFn section of documentation for more info
*/
var thumbSelector = ":nth-child(" + (index+1) + ")", // css :nth-child start at 1
thumbImg = container.children(thumbSelector).children(),
rect = thumbImg.offset();
return { x: rect.left, y: rect.top, w: thumbImg.width() };
};
},
getGallery: function() {
return this.gallery;
}
};
$.fn.photoswipe = function() {
return Photoswipe.initialize(this);
};
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment