Petre Gabriel
Petre Gabriel

Reputation: 141

How to add prev/next navigation to a simple JQuery gallery?

I have a simple image gallery slider with thumbnails under(as you will see in jsfiddle).When I click on a smaller one,big one loads. So far o good. Now I need Prev/Next buttons, to select both small and big one, and I don't know how to add to this script. I am kinda noobish with JQuery. Any kind of help will be welcome. Thanks!

$(function(){
    $("#big-image img:eq(0)").nextAll().hide();
    $(".small-images img").click(function(e){
        var $this = $(this),
            index = $this.index();
        $(".small-images img").removeClass('selected');
        $this.addClass('selected');
        $("#big-image img").eq(index).show().siblings().hide();
    });
});

http://jsfiddle.net/Qhdaz/6/

Upvotes: 1

Views: 2570

Answers (2)

Ram
Ram

Reputation: 144689

I'd suggest:

$(function() {
    // cache the collection for better performance
    var $big= $("#big-image img");
    var $small = $('.small-images img');

    // listen to the click event of the thumbnails
    $small.click(function(e){
        $small.removeClass('selected');
        var i = $(this).addClass('selected').index();
        $big.hide().eq(i).show();
    }).first().click();

    // listen to click event of the next and prev buttons
    // and trigger the click event for the target thumbnail
    $('.next, .prev').click(function() {
        var m = $(this).hasClass('next') ? 'next' : 'prev';
        var $t = $small.filter('.selected')[m]();
        if ($t.length) {
            $small.eq($t.index()).click();
        }
    });
});

http://jsfiddle.net/tghtgdhx/

Upvotes: 1

Sam Battat
Sam Battat

Reputation: 5745

NOTE: add a selected class to the first image in your markup

<img class="selected" src="http://lorempixel.com/100/50/sports/1/">

JS:

$('#next').click(function(){ 
    var $selected = $('.selected');
    var index = $selected.next('img').index();
    if(index == -1){
        index = 0;
    }
    var $curr = $(".small-images img").eq(index);
    $(".small-images img").removeClass('selected');
    $curr.addClass('selected');
    $("#big-image img").eq(index).show().siblings().hide();
});

$('#prev').click(function(){ 
    var $selected = $('.selected');
    var index = $selected.prev('img').index();
    var $curr = $(".small-images img").eq(index);
    $(".small-images img").removeClass('selected');
    $curr.addClass('selected');
    $("#big-image img").eq(index).show().siblings().hide();
});

DEMO: http://jsfiddle.net/Qhdaz/616/

Upvotes: 0

Related Questions