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 ));
@o-l-e
Copy link

o-l-e commented Mar 8, 2015

@kshnurov this is brilliant!
I have been searching for a solution like this for ages, since i am not very good with pure js.
Thanks a lot.

Any chance you may have done anything similar with responsive images + photoswipe?
I am trying to find out how to serve responsive images using photoswipe with inline data-attributes, like for example, data-small="small.jpg" data-large="large.jpg" etc. The documentation shows how to serve images programatically with pure js, but it is way over my head, and i am afraid to ask, since photoswipe clearly does not depend on jquery or methods that affect performance.

Anyway, thanks again for the snippet!

@haydur
Copy link

haydur commented Mar 13, 2015

Can you please post sample gallery markup that your plugin would work with? I am assuming it doesn't work with PhotoSwipe's gallery markup...

@o-l-e
Copy link

o-l-e commented Mar 14, 2015

@haydur i got it working, try this, and remember to place all linked files in a folder /dist. Also this gist as a file "jquery.photoswipe.js":

Head:

<link rel="stylesheet" href="dist/photoswipe.css" />
<link rel="stylesheet" href="dist/default-skin/default-skin.css" />

Markup:

<h2>First gallery:</h2>
<div class="my-simple-gallery">
    <div>
        <a href="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_b.jpg" data-size="964x1024">
            <img src="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_m.jpg" alt="" />
            <figure>This is dummy caption 1.1.</figure>
        </a>
    </div>
    <div>
        <a href="https://farm7.staticflickr.com/6175/6176698785_7dee72237e_b.jpg" data-size="1024x683">
            <img src="https://farm7.staticflickr.com/6175/6176698785_7dee72237e_m.jpg" alt="" />
            <figure>This is dummy caption 1.2.</figure>
        </a>
    </div>
    <div>
        <a href="https://farm6.staticflickr.com/5023/5578283926_822e5e5791_b.jpg" data-size="1024x768">
            <img src="https://farm6.staticflickr.com/5023/5578283926_822e5e5791_m.jpg" alt="" />
            <figure>This is dummy caption 1.3.</figure>
        </a>
    </div>
</div>

<h2>Second gallery:</h2>
<div class="my-simple-gallery">
    <div>
        <a href="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_b.jpg" data-size="964x1024">
            <img src="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_m.jpg" alt="" />
            <figure>This is dummy caption 2.1.</figure>
        </a>
    </div>
    <div>
        <a href="https://farm7.staticflickr.com/6175/6176698785_7dee72237e_b.jpg" data-size="1024x683">
            <img src="https://farm7.staticflickr.com/6175/6176698785_7dee72237e_m.jpg" alt="" />
            <figure>This is dummy caption 2.2.</figure>
        </a>
    </div>
    <div>
        <a href="https://farm6.staticflickr.com/5023/5578283926_822e5e5791_b.jpg" data-size="1024x768">
            <img src="https://farm6.staticflickr.com/5023/5578283926_822e5e5791_m.jpg" alt="" />
            <figure>This is dummy caption 2.3.</figure>
        </a>
    </div>
</div>

<h2>Third gallery:</h2>
<div class="my-simple-gallery">
    <div>
        <a href="https://farm3.staticflickr.com/2567/5697107145_a4c2eaa0cd_o.jpg" data-size="1024x1024">
            <img src="https://farm3.staticflickr.com/2567/5697107145_3c27ff3cd1_m.jpg" alt="" />
            <figure>This is dummy caption 3.1.</figure>
        </a>
    </div>
    <div>
        <a href="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_b.jpg" data-size="964x1024">
            <img src="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_m.jpg" alt="" />
            <figure>This is dummy caption 3.2.</figure>
        </a>
    </div>
    <div>
        <a href="https://farm7.staticflickr.com/6175/6176698785_7dee72237e_b.jpg" data-size="1024x683">
            <img src="https://farm7.staticflickr.com/6175/6176698785_7dee72237e_m.jpg" alt="" />
            <figure>This is dummy caption 3.3.</figure>
        </a>
    </div>
</div>

<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="pswp__bg"></div>
    <div class="pswp__scroll-wrap">
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"> </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"> </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>

Scripts:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="dist/photoswipe.js"></script>
<script src="dist/photoswipe-ui-default.js"></script>
<script src="dist/jquery.photoswipe.js"></script>
<script>
    // init with options
    $('.my-simple-gallery').photoswipe({
        bgOpacity: 0.01,
        loop: true
    });
</script>

PS: Note that i have added an extra div around each a-tag for my own testing purposes.

@inlikealion
Copy link

@kshnurov @o-l-e - did you ever get anywhere with updating this example for responsive images?

@o-l-e
Copy link

o-l-e commented Apr 1, 2015

@inlikealion no i didn't, and have searced through the entire internet to find a solution.
I would die for a solution to responsive images that changes according to browser size.
Does anyone else have a clue how to do this?

@o-l-e
Copy link

o-l-e commented Apr 10, 2015

I had some help from a friend (Paulius Friedt) to handle responsive images based on this gist.

@kshnurov feel free to create a gist and suggest edits, as it may need some improvement.

I created a pen so you can see how it works:
http://codepen.io/o-l-e/pen/PwrRWp

Ps: it is experimental, and i would not really know how to improve it myself.

@haydur
Copy link

haydur commented Jun 17, 2015

Hi there, any idea how I could add the destroy option to your JQuery version? I am new loading slide elements and I would like to destroy and rebuild the galley on load of those new elements.

Or can you add code to your plugin to destroy any previously created array of slides before creating it?

@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