Reputation: 1045
I'm trying to set up an image gallery where you can click a thumb and from that you can then use next and prev buttons. My issue is the user can initially click any image which I need to detect and the workout which the next or previous image will be and replace the display src with the src of the next image. I'm only trying to get the next button working first as the previous will work on the same principle. I have been trying to use the .next() but its really got me baffled.
Any help with this would be great.
Here's a jsfiddle of what I have and below is the jquery I've written, the problem is the bottom bit for the next button:
var numImgs = $('div.locationGallery .polaroidImage').length;
var prevImages = $('.polaroidImage').prevAll().length;
var thisImage;
var imageClicked;
var nextImage;
var nextImage;
$('.polaroidImage').click(function(){
var prevImages = $(this.parentNode).prevAll().find('.polaroidImage').length;
if(prevImages > 0){
$('.prev').show();
}else{
$('.prev').hide();
}
if(prevImages == (numImgs - 1)){
$('.next').hide();
}else{
$('.next').show();
}
});
$(".thumb").click(function(){
imageClicked = '';
imageClicked = $(this).attr('src');
$(".imageDisplay").find('img').remove();
$(".imageDisplay").append("<img src='"+imageClicked+"' />")
});
$('.next').click(function(){
nextImage = $('.imageContainer').next('img').attr('src');
alert(nextImage);
});
Upvotes: 2
Views: 16336
Reputation: 4984
Here is an example with working prev and next buttons: http://jsfiddle.net/8FMsH/1/ On thumb click you need to save the current image:
$(".thumb").click(function(){
imageClicked = $(this);
$(".imageDisplay").find('img').remove();
$(".imageDisplay").append("<img src='"+imageClicked.attr('src')+"' />")
});
$('.next').click(function(){
imageClicked.closest('.imageContainer').next().find('img').trigger('click');
});
$('.prev').click(function(){
imageClicked.closest('.imageContainer').prev().find('img').trigger('click');
});
Upvotes: 5
Reputation: 29925
I've updated your code by setting adding a class of selected
onto the currently selected image and using that to "find" the next thumb.
This seems quite contrived though, and it might be a bit easier if you just maintained some kind of data structure, e.g. an array or object or something which might make it a bit easier, rather than relying on the DOM to do everything.
Upvotes: 0
Reputation: 15053
You need to set the current image on click:
thisImage = $(this).closest('.imageContainer');
Then change the code on the next-click to this:
nextImage = thisImage.next().find('.thumb').attr('src');
See the example at http://jsfiddle.net/c9Jkv/24/
Upvotes: 1