dimsemenov / PhotoSwipe

JavaScript image gallery for mobile and desktop, modular, framework independent
http://photoswipe.com
MIT License
24.27k stars 3.31k forks source link

Get item on beforeChange and afterChange events #909

Closed haroldmuns closed 9 years ago

haroldmuns commented 9 years ago

How can I get the item from the slide if either the beforeChange or afterChange event is fired?

So rather than:

pswp.listen('afterChange', function() { });

It be:

pswp.listen('afterChange', function($item) { });

dimsemenov commented 9 years ago

pswp.currItem

haroldmuns commented 9 years ago

Is there a way to get the previous and next items as well?

dimsemenov commented 9 years ago

pswp.items pswp.getCurrentIndex()

http://photoswipe.com/documentation/api.html

azaharakis commented 8 years ago

Hi, any plans to pass in item as a parameter, the current implementation makes it very hard to write unit tests. Great Library btw!!

treiber commented 8 years ago

I second that. I can't seem to get this functionality to properly work with my own code.

mastef commented 6 years ago

Note : beforeChange gives you the indexDifference as first parameter.

So if you just opened the gallery, it will be null. If you went from 0 -> 1, it will be 1. You can get the previous index with :

         pswp.listen('beforeChange', function(indexDiff) {
                  var previousItem = (pswp.getCurrentIndex() - indexDiff);
         });
phoenixdev-kl commented 5 years ago

@mastef Lets assume you have 4 items. Problem with your approach is that you get invalid index (-1 instead of 3) when the current item is the first one and you are trying to access the previous one. Good news is that you don't need to do all this calculation, simply use pswp.currItem as suggested by @dimsemenov earlier. The name "beforeChange" might be confusing here as pswp.currItem already contains the "next" item.

mastef commented 5 years ago

@phoenixdev-kl You can use the logic from _getLoopedId which will transform an index like -1 to a valid one. My comment was based on fetching the previously shown slide, not the current/next one.

I think I wrote that initial comment because the parameter is undocumented and not mentioned in the docs.

phoenixdev-kl commented 5 years ago

@mastef Cool ... didn't know about _getLoopedId! 👍 And I absolutely agree that indexDiff parameter should get mentioned in the docs.

@dimsemenov I could add it to the docs, any requirements for pull requests?

jasomdotnet commented 1 year ago

2023 snippet how to get current slide index:

var gallery = new PhotoSwipe( ...
gallery.init();

...

gallery.on('change', () => {
   console.log(gallery); // to find out current option name
   console.log(gallery.currIndex);
});