Search code examples
jqueryimagefindjquery-selectorsgallery

jquery find next image after the clicked instance


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);
});

Solution

  • 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');
    });