Reputation: 85
I wrote some script to give my gallery a lightbox style gallery, and I want to be able to go through it with the left and right chevrons I added, so I added the function to do this. But while my left function loops through the gallery to the start and then to the end to give the image of a seamless loop, my right function doesn't work, it goes directly to the final image and then will not continue. Can anyone suggest why this is? What am I doing wrong here,
var currentImage;
$(document).ready(function() {
$('.lightboxBG').hide();
});
$(document).ready(function(){
$('.galleryphoto').click(function()
{
var image_href = $(this).attr("src");
$('.lightboxBG').show();
$('.lightboxIMG').attr("src",image_href);
currentImage = image_href;
});
var images = $("img.galleryphoto").map(function() {
return $(this).attr("src");
});
var left = $('.fa-chevron-left');
var right = $('.fa-chevron-right');
//here is the function which doesn't want to work.
right.click(function(){
for(var j = 0; j < images.length; j++){
if(images[j]=== currentImage){
if(images[j+1] !== undefined){
$('.lightboxIMG').attr("src", images[j+1]);
currentImage = images[j+1];
}
else{$('.lightboxIMG').attr("src", images[0]);
currentImage = images[0];
}
}
}
});
// here is the function which works nicely.
left.click(function(){
for(var i = 0; i < images.length; i++){
if(images[i]=== currentImage){
if(images[i-1] !== undefined){
$('.lightboxIMG').attr("src", images[i-1]);
currentImage = images[i-1];
}
else{$('.lightboxIMG').attr("src", images[images.length-1])
currentImage = images[images.length-1];
}
}
}
});
$('.fa-window-close').click(function(){
$('.lightboxBG').hide();
})
});
Upvotes: 1
Views: 32
Reputation: 39280
First I would advice you to use something like vs code so you could post properly aligned code, this mess is really hard to read.
The following should do the trick:
$(document).ready(function() {
var currentIndex;
const imageUrls = Array.from(
$("img.galleryphoto").map(function() {
return $(this).attr("src");
})
),
next = function(direction){
currentIndex = currentIndex + direction;
if(currentIndex>=imageUrls.length){
currentIndex = 0;
}
if(currentIndex<0){
currentIndex = imageUrls.length-1;
}
$('.lightboxIMG').attr("src", imageUrls[currentIndex]);
};
$('.lightboxBG').hide();
//changed this to img.galleryphoto so it's the same as imageUrls
$('img.galleryphoto').click(function(){
currentIndex = imageUrls.indexOf($(this).attr("src"));
$('.lightboxBG').show();
$('.lightboxIMG').attr("src",imageUrls[currentIndex]);
});
//here is the function which doesn't want to work.
$('.fa-chevron-right').click(function(){
next(1);
});
// here is the function which works nicely.
$('.fa-chevron-left').click(function(){
next(-1);
});
$('.fa-window-close').click(function(){
$('.lightboxBG').hide();
});
});
Upvotes: 1