Ajii Noguerra
Ajii Noguerra

Reputation: 69

Jquery Image gallery with Next/Previous buttons doesn't work correctly

I'm trying to create a slide gallery of images. It doesn't need to run automatically. I just want it to have a previous and next button so the user can navigate manually.

My problem is my code doesn't work. The NEXT button, it only jumps to the second image and never goes to the remaining image when I try clicking it again. The PREVIOUS button when clicked, should show the last image or the previous one but it doesn't.

Please help me out. See my code here

Upvotes: 0

Views: 500

Answers (1)

Barbara Laird
Barbara Laird

Reputation: 12717

Your problem is that you are not removing the previous class before you add it to the current item. So once you've hit next, you have 2 items that are previous and it finds the first one.

$('.next').click(function(event){
    event.preventDefault();

    $('.previous').removeClass('previous');

    $('.current').removeClass('current').addClass('previous');
    $('.previous').hide("slide",{direction: 'left'}, 500);

    var previousId = parseInt($('.previous').attr('id'));

    $('#'+(previousId+1)).show("slide", {direction: 'right'}, 500).addClass('current');

});

$('.prev').click(function(event){
    event.preventDefault();

            $('.previous').removeClass('previous');

    $('.current').removeClass('current').addClass('previous');
    $('.previous').hide("slide",{direction: 'right'}, 500);

    var previousId = parseInt($('.previous').attr('id'));
    var Id = parseInt($('.current').attr('id'));


    $('#'+(previousId-1)).show("slide", {direction: 'left'}, 500).addClass('current');

Once you have that fixed, you'll need to take care of the case where you've hit your last image. Do you want to stay on that image, or circle around?

Upvotes: 2

Related Questions