Skip to content

Instantly share code, notes, and snippets.

@kshnurov
Created February 23, 2015 23:37
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save kshnurov/8b175b8798d4a907e47b to your computer and use it in GitHub Desktop.
Save kshnurov/8b175b8798d4a907e47b to your computer and use it in GitHub Desktop.
PhotoSwipe: init from DOM using jQuery
(function( $ ) {
$.fn.photoswipe = function(options){
var galleries = [],
_options = options;
var init = function($this){
galleries = [];
$this.each(function(i, gallery){
galleries.push({
id: i,
items: []
});
$(gallery).find('a').each(function(k, link) {
var $link = $(link),
size = $link.data('size').split('x');
if (size.length != 2){
throw SyntaxError("Missing data-size attribute.");
}
$link.data('gallery-id',i+1);
$link.data('photo-id', k);
var item = {
src: link.href,
msrc: link.children[0].getAttribute('src'),
w: parseInt(size[0],10),
h: parseInt(size[1],10),
title: $link.data('title'),
el: link
}
galleries[i].items.push(item);
});
$(gallery).on('click', 'a', function(e){
e.preventDefault();
var gid = $(this).data('gallery-id'),
pid = $(this).data('photo-id');
openGallery(gid,pid);
});
});
}
var parseHash = function() {
var hash = window.location.hash.substring(1),
params = {};
if(hash.length < 5) {
return params;
}
var vars = hash.split('&');
for (var i = 0; i < vars.length; i++) {
if(!vars[i]) {
continue;
}
var pair = vars[i].split('=');
if(pair.length < 2) {
continue;
}
params[pair[0]] = pair[1];
}
if(params.gid) {
params.gid = parseInt(params.gid, 10);
}
if(!params.hasOwnProperty('pid')) {
return params;
}
params.pid = parseInt(params.pid, 10);
return params;
};
var openGallery = function(gid,pid){
var pswpElement = document.querySelectorAll('.pswp')[0],
items = galleries[gid-1].items,
options = {
index: pid,
galleryUID: gid,
getThumbBoundsFn: function(index) {
var thumbnail = items[index].el.children[0],
pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
rect = thumbnail.getBoundingClientRect();
return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
}
};
$.extend(options,_options);
var gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
}
// initialize
init(this);
// Parse URL and open gallery if it contains #&pid=3&gid=1
var hashData = parseHash();
if(hashData.pid > 0 && hashData.gid > 0) {
openGallery(hashData.gid,hashData.pid);
}
return this;
};
}( jQuery ));
@prohtex
Copy link

prohtex commented Jul 3, 2015

Thanks! I implemented this modified version on my site. First, I parse the URL hash to see if there is a PID. Then I call parseGallery(PID). This launches PhotoSwipe if there is a PID in the URL (the expected behavior).

function parseGallery(pid) {

    var image = [];

    var options = {
        bgOpacity: 0.9,
        showHideOpacity: true,
        galleryUID: galleryId,
            shareButtons: [
            {id:'email', label:'Email Link', url:'mailto:?body={{url}}', download:true},
            {id:'download', label:'Download image', url:'{{raw_image_url}}', download:true}
            ],
        history:true,
        galleryPIDs:true,
        index:0
        }

    var $pic = $('.container'),

    getItems = function() {
        var items = [];
        $pic.find('a.go').each(function() {
            var $href   = $(this).attr('href'),
                $size   = $(this).data('size').split('x'),
                $width  = $size[0],
                $height = $size[1],
                $name   = $(this).attr('name'),
                $rev    = $(this).attr('data-caption');
            var item = {
                src : $href,
                w   : $width,
                h   : $height,
                pid : $name,
                title : $rev
                }
            items.push(item);
        });
    return items;
    }

    var items = getItems();

    $.each(items, function(index, value) {
        image[index]        = new Image();
        image[index].src    = value['src'];
        });

    $pic.on('click', 'li', function(event) {
        event.preventDefault();
        options.index = $(this).index();
        var lightBox = new PhotoSwipe($('.pswp')[0], PhotoSwipeUI_Default, items, options);
        lightBox.init();
        });

    if (pid) {
        options.index = pid;
        var lightBox = new PhotoSwipe($('.pswp')[0], PhotoSwipeUI_Default, items, options);
        lightBox.init();
        }

    }

@NekoStudio
Copy link

Hello, just sorry for my bad English. The problem is this, there is a picture, when you hover over it, there are icons, how to make that PhotoSwipe launched by clicking on the icon? Thanks in advance

@NurulFitria
Copy link

hi @o-l-e, its possible if i just use 1 image size but i want to be responsive image? like img-responsive class in bootstrap .

@swchok
Copy link

swchok commented Jun 11, 2016

Hi there,

The above creates separate galleries for "div.my-simple-gallery".
How can I modify the code so that there is only 1 gallery for all child elements?

eg.

<div class="my-simple-gallery">
<img 1>
</div>
<div class="my-simple-gallery">
<img 2>
</div>

etc..

Apologies as I'm not well versed in JS. Any help would be greatly appreciated thank you!

@or247
Copy link

or247 commented Sep 6, 2016

@kshnurov this is awesome, just what I need. Notice one weird thing, when you Parse URL and open gallery in new window, if it's pid1 of each gallery it updates to pid2 and shows the second image.

Looking at the fix just now but thought I'd point it out.... thanks for the code!

@monobasic
Copy link

monobasic commented Apr 4, 2018

In the openGallery() function, options.index should be pid-1 instead of just pid, guess index starts from zero.. -> this fixes deep linking to the first image.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment