Plase see title. I would like to achieve the following:
1. On Mobile: In PhotoSwipe, when a swipe to view next image is detected (when already viewing last image), Close PhotoSwipe.
2. On Mobile: Same as the above but when viewing the 1st image. When already viewing 1st image and swipe to show the previous image is detected, Close PhotoSwipe.
3. On Desktop: Using the code below, when the 1st image is viewed, the left arrow PhotoSwipe UI button gets hidden (because there is no previous image to show) and the left arrow key of the keyboard gets disabled.
The goal here is when viewing the first image and the left arrow key on the keyboard is pressed, instead of doing nothing (or looping to the last image), PhotoSwipe gallery to close itself.
Here is a jsfiddle showing the current state of the code:
https://jsfiddle.net/bezq08oc/
Perhaps an approach could be to re-enable loop and in its place to inject code to close the gallery instead of looping it?
loop: false
I am using the code below to:
- Hide the not needed arrow when viewing first image or last image.
- Disable left and right arrow keys on the keyboard when viewing first image or last image.
This will hide the left arrow on first image and right arrow on last image.
It will also work when the keyboard left and right keys are used to change the images.
// Initialize PhotoSwipe
var gallery = new PhotoSwipe($pswp, PhotoSwipeUI_Default, container, options);
gallery.init();
// disable html-arrows control (Hide left arrow on first image and right arrow on last image)
// Code below works only when PhotoSwipe Gallery loads
gallery.getCurrentIndex() === 0 ? $('.pswp__button--arrow--left').hide() : $('.pswp__button--arrow--left').show();
gallery.getCurrentIndex()+1 === gallery.items.length ? $('.pswp__button--arrow--right').hide() : $('.pswp__button--arrow--right').show();
// disable html-arrows control (Hide left arrow on first image and right arrow on last image)
// Code below works when PhotoSwipe Gallery is already opened
gallery.listen('beforeChange', function() {
gallery.getCurrentIndex() === 0 ? $('.pswp__button--arrow--left').hide() : $('.pswp__button--arrow--left').show();
gallery.getCurrentIndex()+1 === gallery.items.length ? $('.pswp__button--arrow--right').hide() : $('.pswp__button--arrow--right').show();
}
);
// disable keys left+right control
$('body').keydown(function(e) {
// key left
if ((e.keyCode || e.which) == 37) {
if (gallery.getCurrentIndex() === 0) {
gallery.options.arrowKeys = false;
} else {
gallery.options.arrowKeys = true;
}
}
// key right
if ((e.keyCode || e.which) == 39) {
if (gallery.getCurrentIndex()+1 === gallery.items.length) {
gallery.options.arrowKeys = false;
} else {
gallery.options.arrowKeys = true;
}
}
});